0

我有一个主列表,它们有两个字段,分别是名称和评级,在序列化到数组节点之后,我需要为每个对象再添加一个字段,例如我有 json

[{"masterName":"Bruce","rating":30},{"masterName":"Tom","rating":25}]

我有 json 格式的 servisec 列表,看起来像这样

[{"masterName":"Bruce","services":["hair coloring","massage"]},{"masterName":"Tom","services":["hair coloring","haircut"]}]

我需要它看起来像那样

[{"masterName":"Bruce","rating":30,"services":"hair coloring,massage"},{"masterName":"Tom","rating":25,"services":"hair coloring, haircut"}]

使用杰克逊如何做到这一点?

4

1 回答 1

0

我会这样处理它。既然你想使用杰克逊。

首先,我将Master通过添加services(这似乎是一个带有 的数组Strings)来扩展类。

所以这个类看起来像这样:

    public class Master
    {
        private String masterName;
        private int rating;
        private List<String> services = new ArrayList<>(); // THE NEW PART
        
        // Whatever you have else in your class
    }

然后你可以得到你的 JSON 数组,我想它是String为了简单起见。将此数组序列化为带有Master对象的数组,然后您可以按上述方式添加服务。

例如

    String yourJsonString = "[{\"masterName\":\"Bruce\",\"rating\":30},{\"masterName\":\"Tom\",\"rating\":25}]";
    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    List<Master> theListOfMasters = new ArrayList<>();

    // Read them and put them in an Array
    Master[] mastersPlainArr = mapper.readValue(yourJsonString, Master[].class);

    theListOfMasters = new ArrayList(Arrays.asList(mastersPlainArr));

    // then you can get your masters and edit them..

    theListOfMasters.get(0).getServices.add("A NEW SERVICE...");

    // And so on...

    // Then you can turn them in a JSON array again:

    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(theListOfMasters);
于 2021-06-10T06:10:06.250 回答