使用包含数组和自定义字段的Jackson创建有效的JSON [英] Create a valid JSON using Jackson that contains an array and a custom field
问题描述
下面的代码使用Jackson生成JSON,就数据而言是好的,但它不是JSON
My code below to generate a JSON using Jackson, is fine as far as the data is concerned, but its not a JSON
生成的JSON没有传递 JSONLint ,因为它的引号括号和逗号周围的引号。它也反击了我从它中删除了 - 但我很确定我在下面做的事情有问题
The generated JSON doesnt pass JSONLint, because its got quotes around the square brackets and quotes around commas. It also backslashes which I hacked out of it - but Im pretty sure there's something wrong with what Im doing below
这是我正在尝试做的事情:
Here is what I'm trying to do:
JSON应该如下所示(除了 skip
字段,我在此处添加了该字段以突出显示它序列化时将从Object中省略):
The JSON is supposed to look as follows (with the exception of the skip
field which I have added here to highlight that it will be omitted from the Object when serialized):
{
"users": [{
"foo": "abc1",
"bar": "def1",
"skip": "this field is skipped"
}, {
"foo": "abc2",
"bar": "def2",
"skip": "this field is skipped"
}],
"uri": "/users"
}
用户密钥是一组用户 - 上面显示了2个元素。 skip字段不应该是最终json的一部分,但它是每个'user'对象的一部分
The users Key is an array of users - 2 elements shown above. The skip field shouldnt be part of the final json, but its part of each 'user' object
添加URI字段
我的代码如下。它成功跳过'skip'字段,如果消除了奇怪的格式,它就成功构建了几乎是JSON的String。但我承认这段代码很可怕而且它可能会更好(虽然我不知道我是怎么做到这一点)
My code is below. It successfully skips the 'skip' field and it successfully builds a String that is almost a JSON if the weird formatting is eliminated. But I admit this code is horrid and it can be better (although I dont know how since Im new to this)
你问的奇怪格式是什么?
What is the weird formatting you ask?
- 反斜杠(你可以看到我已经使用hackey正则表达式消除了)
- 引用[和]
- 行情,(逗号)
代码:
get("/users", (request, response) -> {
//this is the array of objects
Object[] allUsers = listenUp.get_all_users();
//Ignore this field per ListenUpUser object
String[] ignorableFieldNames = { "skip" };
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by name",
SimpleBeanPropertyFilter.serializeAllExcept(
ignorableFieldNames));
ObjectWriter writer = mapper.writer(filters);
ArrayNode array = mapper.createArrayNode();
for(int i = 0; i < allUsers.length; i++) {
array.add(writer.writeValueAsString(allUsers[i]));
}
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode child = mapper.createObjectNode();
child.put("users", array.toString());
child.put("uri", "/users");
response.status(200);
response.type("application/json");
String a = child.toString().replaceAll("\\\\", "");
return a;
});
这已在文件顶部定义(对于跳过字段逻辑)
This has been defined at the top of the file (for the skip field logic)
@JsonFilter("filter properties by name")
class PropertyFilterMixIn {}
推荐答案
我认为你可以使用 Hashmap< String,Object>
。 Jackson将了解如何将过滤器应用于数组中的 Object
,并且只会跳过它找到的任何其他对象(String / array)。这是演示,适用于我:
I think you can use Hashmap<String, Object>
. Jackson will understand how to apply filter to the Object
in array and will just skip any other object(String/array) it finds. Here is demo, that works for me:
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
public class test12 {
public static void main(String[] args) throws IOException, JSONException {
Object[] allUsers = get_all_users();
String[] ignorableFieldNames = {"skip"};
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by name",
SimpleBeanPropertyFilter.serializeAllExcept(
ignorableFieldNames));
mapper.setFilterProvider(filters);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("users", allUsers);
map.put("uri", "/users");
String result = mapper.writeValueAsString(map);
System.out.println(result);
}
@JsonFilter("filter properties by name")
public static class PropertyFilterMixIn {
}
private static Object[] get_all_users() {
User user1 = new User();
user1.foo = "abc1";
user1.bar = "def1";
user1.skip = "this field is skipped";
User user2 = new User();
user2.foo = "abc2";
user2.bar = "def2";
user2.skip = "this field is skipped";
return new Object[]{user1, user2};
}
public static class User {
public String foo;
public String bar;
public String skip;
}
}
结果:
{
"users" : [ {
"foo" : "abc1",
"bar" : "def1"
}, {
"foo" : "abc2",
"bar" : "def2"
} ],
"uri" : "/users"
}
这篇关于使用包含数组和自定义字段的Jackson创建有效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!