gpt4 book ai didi

java - 使用 Jackson 创建包含数组和自定义字段的有效 JSON

转载 作者:行者123 更新时间:2023-12-01 10:05:02 25 4
gpt4 key购买 nike

下面的代码使用 Jackson 生成 JSON,就数据而言很好,但它不是 JSON

生成的 JSON 未通过 JSONLint ,因为它的方括号周围有引号,逗号周围有引号。它还有我从中删除的反斜杠 - 但我很确定我在下面所做的事情有问题

这是我正在尝试做的事情:

JSON 应该如下所示(除了我在此处添加的 skip 字段以突出显示在序列化时它将从对象中省略):

{
"users": [{
"foo": "abc1",
"bar": "def1",
"skip": "this field is skipped"
}, {
"foo": "abc2",
"bar": "def2",
"skip": "this field is skipped"
}],
"uri": "/users"
}

users 键是一个用户数组 - 上面显示的 2 个元素。跳过字段不应该是最终 json 的一部分,而应该是每个“用户”对象的一部分

添加了 URI 字段

我的代码如下。它成功地跳过了“skip”字段,并且如果消除了奇怪的格式,它会成功构建一个几乎是 JSON 的字符串。但我承认这段代码很糟糕,而且还可以做得更好(尽管我不知道如何做,因为我是新手)

您问的奇怪格式是什么?

  1. 反斜杠(你可以看到我已经使用 hackey 正则表达式消除了)
  2. 引用 [ 和 ]
  3. 引号,(逗号)

代码:

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;
});

这已在文件顶部定义(用于跳过字段逻辑)

@JsonFilter("filter properties by name")
class PropertyFilterMixIn {}

最佳答案

我认为你可以使用Hashmap<String, Object> 。 Jackson 将了解如何将过滤器应用于 Object在数组中,并且只会跳过它找到的任何其他对象(字符串/数组)。这是适合我的演示:

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"
}

关于java - 使用 Jackson 创建包含数组和自定义字段的有效 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com