2012-11-27 211 views
1

我需要使用Jackson庫解析相對複雜的JSON。你們能否建議我應該具備哪些Java類結構以及用什麼Jackson方法來解析以下JSON對象。與Jackson解析複雜的JSON對象

它是這樣的:

{ 
    "firstField": "Something One", 
    "secondField": "Something Two", 
    "thirdField": [ 
    { 
     "thirdField_one": "Something Four", 
     "thirdField_two": "Something Five" 
    }, 
    { 
     "thirdField_one": "Something Six", 
     "thirdField_two": "Something Seven" 
    } 
    ], 
    "fifthField": [ 
    { 
     "fifthField_one": "Something… ", 
     "fifthField_two": "Something...", 
     "fifthField_three": 12345 
    }, 
    { 
     "fifthField_one": "Something", 
     "fifthField_two": "Something", 
     "fifthField_three": 12345 
    } 
    ] 
} 
+0

您是否使用傑克遜解決方案? – andro

回答

1

我多用GSON精通,但我認爲這應該工作。

見StaxMan的下方注:

傑克遜不會自動檢測private字段(它可以被配置爲,與@JsonAutoDetect或全球)。所以字段應該是私有的,用@JsonProperty註釋,或者有匹配的公共getter。

public class MyClass { 
    private String firstField, secondField; 
    private ThirdField thirdField; 
    private FifthField fifthField; 

    public static class ThirdField { 
     private List<ThirdFieldItem> thirdField; 
    } 

    public static class ThirdFieldItem { 
     private String thirdField_one, thirdField_two; 
    } 

    public static class FifthField { 
     private List<FifthFieldItem> fifthField; 
    } 

    public static class FifthField { 
     private String fifthField_one, fifthField_two; 
     private int fifthField_three; 
    } 
} 
+0

正確,除了與Gson不同,傑克遜不會自動檢測私人字段(它可以通過'@ JsonAutoDetect'或全局配置)。所以字段應該是私有的,用'@ JsonProperty'註釋或者具有匹配的公共getter。 – StaxMan

+0

啊,謝謝你StaxMan,很高興知道。我會更新答案。 – antew