[英]JSON to Java object - Unrecognized field, not marked as ignorable
[英]Map JSON to POJO For Processing - Unrecognized field not marked as ignorable
我需要幫助映射以下 JSON 結構以進行進一步處理。
[{
"userId": "11",
"otherId": "a",
"key1": "Tesla",
"key2": "S3",
"behaviour": {
"color": "white",
"size": "S",
"owner": "Mr. A"
}
},
{
"userId": "22",
"otherId": "",
"key1": "Merc",
"key2": "C-Class",
"behaviour": {
"color": "black",
"size": "M",
"isNew": true
}
},
{
"userId": "33",
"otherId": "c",
"key1": "Honda",
"key2": "CRV",
"behaviour": {
"color": "green",
"size": "L",
}
}]
以下是我擁有的 POJO:
public class MainObject {
private String userId;
private String otherId;
private String key1;
private String key2;
private Set<Behaviour> behaviours;
}
public class Behaviour {
private final String name;
private final Object value;
}
我需要獲取 MainObject 列表以進行進一步處理。 在下面嘗試過,但不確定如何映射行為集 -
String inputLine = currentBufferedReader.readLine();
//Above String has complete JSON
ObjectMapper objectMapper = new ObjectMapper();
FirstObject[] firstObjects = objectMapper.readValue(inputLine, FirstObject[].class);
我得到:無法識別的字段未使用上述代碼標記為可忽略。 請建議。
像belwo一樣定義你的類
class MainObject {
public String userId;
public String otherId;
public String key1;
public String key2;
@JsonProperty(value = "behaviour")
public Map<String, String> behaviours;
@Override
public String toString() {
return "MainObject [userId=" + userId + ", otherId=" + otherId + ", key1=" + key1 + ", key2=" + key2
+ ", behaviours=" + behaviours + "]";
}
}
要映射的代碼
public static void main(String[] args) throws IOException {
String array = "[\r\n" +
" {\r\n" +
" \"userId\":\"11\",\r\n" +
" \"otherId\":\"a\",\r\n" +
" \"key1\":\"Tesla\",\r\n" +
" \"key2\":\"S3\",\r\n" +
" \"behaviour\":{\r\n" +
" \"color\":\"white\",\r\n" +
" \"size\":\"S\",\r\n" +
" \"owner\":\"Mr. A\"\r\n" +
" }\r\n" +
" },\r\n" +
" {\r\n" +
" \"userId\":\"22\",\r\n" +
" \"otherId\":\"\",\r\n" +
" \"key1\":\"Merc\",\r\n" +
" \"key2\":\"C-Class\",\r\n" +
" \"behaviour\":{\r\n" +
" \"color\":\"black\",\r\n" +
" \"size\":\"M\",\r\n" +
" \"isNew\":true\r\n" +
" }\r\n" +
" },\r\n" +
" {\r\n" +
" \"userId\":\"33\",\r\n" +
" \"otherId\":\"c\",\r\n" +
" \"key1\":\"Honda\",\r\n" +
" \"key2\":\"CRV\",\r\n" +
" \"behaviour\":{\r\n" +
" \"color\":\"green\",\r\n" +
" \"size\":\"L\"\r\n" +
" }\r\n" +
" }\r\n" +
"]";
ObjectMapper mapper = new ObjectMapper();
MainObject[] objects = mapper.readValue(array, MainObject[].class);
System.out.println(Arrays.asList(objects));
}
輸出
[MainObject [userId=11, otherId=a, key1=Tesla, key2=S3, behaviours={color=white, size=S, owner=Mr. A}],
MainObject [userId=22, otherId=, key1=Merc, key2=C-Class, behaviours={color=black, size=M, isNew=true}],
MainObject [userId=33, otherId=c, key1=Honda, key2=CRV, behaviours={color=green, size=L}]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.