2016-06-28 16 views
0

マップされた値を配列に配置する方法とその配列を反復する方法を理解するのは本当に苦労しています。Jackson JSONからJavaに値を格納する方法

test.json

[ 
    { 
    "Name": "Bob", 
    "Nationality": "", 
    "City": "Chicago", 
    "Phone" : "451232424234" 
    }, 

    ......continues with more objects 
] 

testTemplate.java

//imports 
    @JSONInclude(Json.Include.Non_NULL) 
    @JsonPropertyOrder({"Name,"Nationality","City","Phone"}) 

    Public class testTemplate { 

    @JsonProperty("Name") 
    private String userName; 

    @JsonProperty("Nationality") 
    private String nation; 

    @JsonProperty("City") 
    private String city; 

    @JsonProperty("Phone") 
    private String phone; 

    @JsonProperty("Name") 
    public String getName (String userName) { 
     this.userName = userName; 
    } 

    @JsonProperty("Nationality") 
    public String nation (String nation) { 
     this.nation = nation; 
    } 

    @JsonProperty("City") 
    public String city (String city) { 
     this.city = city; 
    } 

    @JsonProperty("Phone") 
    public String phone (String phone) { 
     this.phone = phone; 
    } 

    public String toString() { 
    return ToStringBuilder.reflectionToString(this); 
    } 

testParse.java

Public Class testParse { 
    List<testParse> test; 
    ObjectMapper mapper; 

    protected void setUp() throws IOException { 
      mapper = new ObjectMapper(); 
      mapper.enable(SerializationFeature.INDENT_OUTPUT(); 
      test = mapper.readValue(this.getClass().getResourcesAsStream("test.json"), 
      mapper.getTypeFactory().constructCollectionType(List.class, testParse.class)); 

私は、最初のコードがやっているまさに明確に、そしてどのように支援する必要がありますJSONプロパティ(名前、国籍、都市、電話番号)をJavaに配置します。

私が理解していることは、プロパティを保持する文字列を作成し、次にtestParseファイルにjsonを読み込み、すべてを "test"(配列として? )

私の目標は、すべての事は、私はそれを読み、「テスト」であり、それを引き出し、のFolderListにそれを置くために開始した場合testParse、です。

public static Map<String, String> userName throws IOException { 
    Map<String, String> folderList = new TreeMap<>(); 
    //Don't know how, but iterate through "test" 
    LineIterator it = new LineIterator(//the method used to read the json file); 
    try { 
     while(it.hasNext()) { 
     String line = it.nextLine(); 
     folderList.put(userName,nation) //can I also put city and phone at once as well or should I create another put: folderList.put(userName, city) 
     return folderList; 

これはどのようにして行われますか? jacksonマッパーを使用した後、jsonのプロパティをfolderListに入れるより良い方法はありますか?

答えて

1

実は、testTemplateは、リフレクションを使用して文字列は、testTemplate.javaの形式を読み取るようジャクソンはここでやっているものは、単に「test.json」からデータを取得している生成されません。テンプレートに基づいて、ObjectMapperオブジェクトに追加する設定だけです.JavaScriptはtest.jsonをオブジェクトJavaの配列に変換します。
P/S:両方の属性にアノテーションを追加したり、POJOクラスの関数を取得する必要はありません。関数や属性のみを取得するだけで、ジャクソンにとっては十分です。

+0

testParse.javaのfolderList配列にオブジェクトを追加する方法を示してください。 – Bobshark

+0

これを実行して取得することができますhttp://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects –

関連する問題