![](/img/trans.png)
[英]Jackson deserialize two different Json representations in one POJO
[英]One POJO for two different JSONs using Jackson
JSON 1:
[
{
"a": 23118,
"b": "3373141",
"c": "abcd",
"d": "d_name",
"override": false,
"qty1": 2000.0,
"qty2": 2000.0,
"qty3": 2000.0,
"qty4": 2000.0,
"update": "01:00:00"
},
{},
{},
...
]
JSON 2:
[
{
"e": 2317418,
"f": "XYZ",
"g": "abcdef",
"h": "h_name",
"override": false,
"qty1": 2000.0,
"qty2": 2000.0,
"qty3": 2000.0,
"qty4": 2000.0
},
{},
{},
...
]
碼:
ObjectMapper objectMapper = new ObjectMapper();
responsePOJO responsePOJOObj = objectMapper.readValue(JSONString, responsePOJO.class);
是否可以使用一個POJO類轉換JSON 1和JSON 2? 或者我必須創建兩個不同的POJO?
你還沒有展示你的responsePOJO
課程的樣子,但是你可以。 您可以做的是像往常一樣創建所有已知字段,然后將未知數存儲為地圖並使用Jacksons JsonAnySetter
注釋。
例如,將其他字段存儲在地圖中,如下所示:
private Map<String, Object> otherFields = new HashMap<>();
@JsonAnySetter
public void set(String name, Object value) {
otherFields.put(name, value)
}
然后傑克遜將為您在標准字段列表中找不到的任何字段調用此set
方法
如果只是某些字段不同,我建議使用2個POJO和一個包含公共字段的公共父類。
abstract class PojoParent {
int qty1;
int qty2;
boolean override;
...
}
class Pojo1 extends PojoParent {
String a;
...
}
class Pojo2 extends PojoParent {
String e;
...
}
只有一個類可能有一些技巧,但我建議采用最簡單和全面的解決方案。
您可以像這樣使用JsonIgnoreProperties
批注:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PojoDeserialize {
public static class ResponsePOJO {
@JsonIgnoreProperties(ignoreUnknown = true)
public String a;
@JsonIgnoreProperties(ignoreUnknown = true)
public String b;
@JsonIgnoreProperties(ignoreUnknown = true)
public String c;
@JsonIgnoreProperties(ignoreUnknown = true)
public String d;
@JsonIgnoreProperties(ignoreUnknown = true)
public String e;
@JsonIgnoreProperties(ignoreUnknown = true)
public String f;
@JsonIgnoreProperties(ignoreUnknown = true)
public String g;
@JsonIgnoreProperties(ignoreUnknown = true)
public String h;
}
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json1 = "{\"a\": 23118,\"b\": \"3373141\",\"c\": \"abcd\",\"d\": \"d_name\"}";
ResponsePOJO resp1 = objectMapper.readValue(json1, ResponsePOJO.class);
assert resp1.a != null;
assert resp1.b != null;
assert resp1.c != null;
assert resp1.d != null;
assert resp1.e == null;
assert resp1.f == null;
assert resp1.g == null;
assert resp1.h == null;
String json2 = "{\"e\": 2317418,\"f\": \"XYZ\",\"g\": \"abcdef\",\"h\": \"h_name\"}";
ResponsePOJO resp2 = objectMapper.readValue(json2, ResponsePOJO.class);
assert resp2.a == null;
assert resp2.b == null;
assert resp2.c == null;
assert resp2.d == null;
assert resp2.e != null;
assert resp2.f != null;
assert resp2.g != null;
assert resp2.h != null;
}
}
所以這樣你可以保留一個類但轉換兩個不同的JSON字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.