2012-09-15 22 views
7

をネストされたI以下のJSON持っている:私はそれを解析するには、次のコードを使用しています解析は、JSON

{ 
    "registration": { 
    "name": "Vik Kumar", 
    "first_name": "Vik", 
    "last_name": "Kumar", 
    "bloodGroup": "B-", 
    "gender": "male", 
    "birthday": "10\/31\/1983", 
    "email": "vik.ceo\u0040gmail.com", 
    "cellPhone": "1234123456", 
    "homePhone": "1234123457", 
    "officePhone": "1234123458", 
    "primaryAddress": "jdfjfgj", 
    "area": "jfdjdfj", 
    "location": { 
     "name": "Redwood Shores, California", 
     "id": 103107903062719 
    }, 
    "subscribe": true, 
    "eyePledge": false, 
    "reference": "fgfgfgfg" 
    } 
} 

を:

JsonNode json = new ObjectMapper().readTree(jsonString); 
JsonNode registration_fields = json.get("registration"); 

Iterator<String> fieldNames = registration_fields.getFieldNames(); 
while(fieldNames.hasNext()){ 
    String fieldName = fieldNames.next(); 
    String fieldValue = registration_fields.get(fieldName).asText(); 
    System.out.println(fieldName+" : "+fieldValue); 
} 

これは正常に動作し、それがある場所以外のすべての値を印刷一種のネスティングレベル。上記のコードと同じトリックをjson.get( "location")に渡してみましたが、うまくいきません。場所に適した方法を提案してください。

+0

「動作しない」とはどういう意味ですか?エラーメッセージが表示されますか?もしそうなら、それは何を言いますか? –

+1

上記のコードが正常に動作することを確認するだけです。しかし、私が場所のフィールドに同じロジックを適用しようとすると、line location_fields.getFieldNames()はnullポインタの例外をスローします。私は最初の行に正しい名前 "location"を渡していると確信しています – Vik

答えて

15

あなたはJsonNode#isObjectを使用して(ネスト)Objectを扱っている場合を検出する必要があります:あなたは、このようなlocationなどのオブジェクトを、到達したときにこのように、あなたがすべて印刷する再帰的printAllと呼ぶことにします

public static void printAll(JsonNode node) { 
    Iterator<String> fieldNames = node.getFieldNames(); 
    while(fieldNames.hasNext()){ 
     String fieldName = fieldNames.next(); 
     JsonNode fieldValue = node.get(fieldName); 
     if (fieldValue.isObject()) { 
      System.out.println(fieldName + " :"); 
      printAll(fieldValue); 
     } else { 
      String value = fieldValue.asText(); 
      System.out.println(fieldName + " : " + value); 
     } 
    } 
} 

その内部の値。 location以来

org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString); 
org.codehaus.jackson.JsonNode registration_fields = json.get("registration"); 
printAll(registration_fields); 
+1

Txは試してみるといいですね。 – Vik

+1

node.getFieldNames()は使用できません。代わりにnode.fieldNames()を使用しますか? –

+0

パッケージを見せていただきありがとうございます。 –

1

registration内にネストされ、あなたが使用する必要があります。

registration_fields.get("location"); 

をそれを得るために。しかし、それはすでにwhileループによって処理されていません、なぜそれを別々に取得する必要がありますか?

+2

彼は 'location'の内容を印刷したいと考えています。それはオブジェクトなので、* text *の値は空になります。 –

+0

しかし、その場合はどうすればその値を得ることができますか?現在のコード行String fieldValue = registration_fields.get(fieldName).asText()は空白を表示します – Vik

+0

JoãoSilvaの答えを参照してください。 – Barmar