2011-10-29 8 views
3

JSONObjectとJSONArrayを使用して、Androidで以下のJSON文字列を正常に解析できました。 GSONやJacksonと同じ結果を達成したことはありませんでした。誰かがGSONとJacksonでこれを解析するためにPOJO定義を含むコードフラグメントを手伝ってくれますか?GSON/Jackson in Android

{ 
    "response":{ 
     "status":200 
    }, 
    "items":[ 
     { 
      "item":{ 
       "body":"Computing" 
       "subject":"Math" 
       "attachment":false, 
     } 
    }, 
    { 
     "item":{ 
      "body":"Analytics" 
      "subject":"Quant" 
      "attachment":true, 
     } 
    }, 

], 
"score":10, 
"thesis":{ 
     "submitted":false, 
     "title":"Masters" 
     "field":"Sciences",   
    } 
} 
+1

たぶん、あなたは間違っているかもしれないもののアイデアを与えるために、あなたがしてみてくださいでしたPOJO定義を含めることができますか?基本的な考え方は、構造に合わせることです。 – StaxMan

+0

また、質問を投稿する際に、コードやJSONの例が有効で正しいことを確認することをおすすめします。元の質問のJSONの例は無効です。このスレッドから何が得られたのかを推測したり、助けてくれる人がいます。 http://jsonlint.comを使用すると、JSONを迅速かつ簡単に検証できます。 –

答えて

8

マッチングJavaデータ構造への/からの/デシリアライズ(元の質問に無効なJSONに類似)JSONをシリアライズするGsonジャクソンを使用して簡単な例です。

JSON:

{ 
    "response": { 
     "status": 200 
    }, 
    "items": [ 
     { 
      "item": { 
       "body": "Computing", 
       "subject": "Math", 
       "attachment": false 
      } 
     }, 
     { 
      "item": { 
       "body": "Analytics", 
       "subject": "Quant", 
       "attachment": true 
      } 
     } 
    ], 
    "score": 10, 
    "thesis": { 
     "submitted": false, 
     "title": "Masters", 
     "field": "Sciences" 
    } 
} 

マッチングJavaデータ構造:

class Thing 
{ 
    Response response; 
    ItemWrapper[] items; 
    int score; 
    Thesis thesis; 
} 

class Response 
{ 
    int status; 
} 

class ItemWrapper 
{ 
    Item item; 
} 

class Item 
{ 
    String body; 
    String subject; 
    boolean attachment; 
} 

class Thesis 
{ 
    boolean submitted; 
    String title; 
    String field; 
} 

ジャクソン例:

import java.io.File; 

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.setVisibilityChecker( 
     mapper.getVisibilityChecker() 
     .withFieldVisibility(Visibility.ANY)); 
    Thing thing = mapper.readValue(new File("input.json"), Thing.class); 
    System.out.println(mapper.writeValueAsString(thing)); 
    } 
} 

Gson例:

import java.io.FileReader; 

import com.google.gson.Gson; 

public class GsonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Gson gson = new Gson(); 
    Thing thing = gson.fromJson(new FileReader("input.json"), Thing.class); 
    System.out.println(gson.toJson(thing)); 
    } 
}