简体   繁体   English

将嵌套的 Java 对象序列化为 json

[英]Serializing nested Java Objects into json

There is a java object that refers to another object, and that object refers to another one.有一个 java object 指的是另一个 object,而 ZA8CFDE6331BD59EB2AC966F8911C4B 指的是另一个。 All these three objects can be serialized into json.所有这三个对象都可以序列化为 json。

All classes have appropriate Jackson annotation:所有类都有相应的 Jackson 注释:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.ANY, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
class A {
    B b;
    @JsonProperty("components")
    public String getComponents() {
       /***/
    }
}

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
class B {
   @JsonProperty 
   String message;
   @JsonProperty
   Long id;
   @JsonIgnore
   C c;
}

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
Class C {
   @JsonProperty 
   String param1;
   @JsonProperty
   String param2;
}

Currently the getComponents method in class A looks like this:目前 class A 中的getComponents方法如下所示:

    public String getComponents() {
         JSONObject components = new JSONObject();
         components.put("b", b);
         components.put("c", c);
         return components.toString();
    }

For components property I expect to see the following in the json:对于components属性,我希望在 json 中看到以下内容:

"components": { "b": {"message":"", id:1}, "c": {"param1":"", "param2":""}}

But currently it returns the reference to the objects但目前它返回对对象的引用

"components": { "b": "com.myproject.B@6by789ae", "c": "com.myproject.C@8io287ko"}

Considering that each object has the ability to be turned into json, why doesn't JSONObject.toString recursively loop over them and turn each into its json representation?考虑到每个 object 都有能力转换为 json,为什么JSONObject.toString不递归循环它们并将每个转换为 json 表示? Is there any mechanism that I use?有什么我使用的机制吗?

Ok.好的。 I think I found a solution.我想我找到了解决办法。 I turned components from JSONObject into Map<String, Object> and jackson seems to be handling the rest:我将JSONObject中的components转换为Map<String, Object>并且 jackson 似乎正在处理 rest:

public Map<String, Object> getComponents() {
     Map<String, Object> components = new HashMap<>();
     components.put("b", b);
     components.put("c", c);
     return components;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM