2015-09-08 11 views
6

gsonを使用してjsonを解析するにはどうすればよいですか?私は複数のオブジェクト型を持つjson配列を持っていますが、私はこの構造を保存するためにどのようなオブジェクトを作成する必要があるのか​​分かりません。私はjsonのデータ形式を変更することはできません(私はサーバーを制御しません)。 gsonや他のライブラリでこのjson配列を解析することはできますか?gsonで複数のオブジェクトを持つjson配列を解析するにはどうすればよいですか?

これは、JSONコードブロックです:

[ 
    { 
    "type": 1, 
    "object": { 
     "title1": "title1", 
     "title2": "title2" 
    } 
    }, 
    { 
    "type": 2, 
    "object": [ 
     "string", 
     "string", 
     "string" 
    ] 
    }, 
    { 
    "type": 3, 
    "object": [ 
     { 
     "url": "url", 
     "text": "text", 
     "width": 600, 
     "height": 600 
     }, 
     { 
     "url": "url", 
     "text": "text", 
     "width": 600, 
     "height": 600 
     } 
    ] 
    }, 
    { 
    "type": 4, 
    "object": { 
     "id": 337203, 
     "type": 1, 
     "city": "1" 
    } 
    } 
] 
+0

こんにちは!私の答えはまだ読んだことがありますか? – BNK

答えて

5

このjson構造は本質的にgson-unfriendlyです。つまり、「オブジェクト」キーが動的なタイプを参照しているため、これをjavaで完全にモデル化することはできません。

String json = "{ ... json string ... }"; 
Gson gson = new Gson(); 
Models model = gson.fromJson(json, Models.class); 


for (Models.Container container : model) { 

    String innerJson = gson.toJson(container.object); 

    switch(container.type){ 
     case 1: 
      Models.Type1Object type1Object = gson.fromJson(innerJson, Models.Type1Object.class); 
      // do something with type 1 object...         
      break; 
     case 2: 
      String[] type2Object = gson.fromJson(innerJson, String[].class); 
      // do something with type 2 object... 
      break; 
     case 3: 
      Models.Type3Object[] type3Object = gson.fromJson(innerJson, Models.Type3Object[].class); 
      // do something with type 3 object... 
      break; 
     case 4: 
      Models.Type4Object type4Object = gson.fromJson(innerJson, Models.Type4Object.class); 
      // do something with type 4 object... 
      break; 

    } 
} 

最終的に最善の解決策は、JSON構造を得ることです:

public class Models extends ArrayList<Models.Container> { 

    public class Container { 
     public int type; 
     public Object object; 
    } 

    public class Type1Object { 
     public String title1; 
     public String title2; 
    } 

    public class Type3Object { 
     public String url; 
     public String text; 
     public int width; 
     public int height; 
    } 

    public class Type4Object { 
     public int id; 
     public int type; 
     public int city; 
    } 

} 

が続いタイプにいくつかの厄介なスイッチとオブジェクトフィールドの操作を行います。あなたはこの構造にできる最善のは、モデル、それとても似ていますjavaと互換性のあるものに変更されました。

例えば:

[ 
    { 
    "type": 1, 
    "type1Object": { 
     "title1": "title1", 
     "title2": "title2" 
    } 
    }, 
    { 
    "type": 2, 
    "type2Object": [ 
     "string", 
     "string", 
     "string" 
    ] 
    }, 
    { 
    "type": 3, 
    "type3Object": [ 
     { 
     "url": "url", 
     "text": "text", 
     "width": 600, 
     "height": 600 
     }, 
     { 
     "url": "url", 
     "text": "text", 
     "width": 600, 
     "height": 600 
     } 
    ] 
    }, 
    { 
    "type": 4, 
    "type4Object": { 
     "id": 337203, 
     "type": 1, 
     "city": "1" 
    } 
    } 
] 
+0

ありがとう、それは私のために働く。 – xiangmao

1

あなたは非常に簡単にあなたのモデルクラスのメソッドを設定することができます。 StringRequestを作成するだけです。私はJSONあなたからあなたのモデルクラスを生成するのにthisを使用している

List<YourModelClass> inpList; 
StringRequest greq = new StringRequest(Request.Method.POST, yourURL, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       try { 
         Log.d("response array===> ", response.toString()); 

         Type type = new TypeToken<List<YourModelClass>>(){}.getType(); 
         inpList = new Gson().fromJson(response, type); 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       error.printStackTrace(); 

      } 
     }){ 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       Map<String, String> params = new HashMap<String, String>(); 
       //return params back to server, if any 
      } 
     }; 

     yourVolley.getRequestQueue().add(greq); 

:以下は抜粋です。あなたの内部オブジェクトはJSONオブジェクトまたはJSONの配列にすることができますので、私が使用するので

:あなたの問題については

package com.example; 

import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 

@Generated("org.jsonschema2pojo") 
public class YourModelClass { 

@Expose 
private Integer type; 
@Expose 
private Object object; 

/** 
* 
* @return 
* The type 
*/ 
public Integer getType() { 
return type; 
} 

/** 
* 
* @param type 
* The type 
*/ 
public void setType(Integer type) { 
this.type = type; 
} 

/** 
* 
* @return 
* The object 
*/ 
public Object getObject() { 
return object; 
} 

/** 
* 
* @param object 
* The object 
*/ 
public void setObject(Object object) { 
this.object = object; 
} 

} 
-----------------------------------com.example.Object.java----------------------------------- 

package com.example; 

import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 

@Generated("org.jsonschema2pojo") 
public class Object { 

@Expose 
private Integer id; 
@Expose 
private Integer type; 
@Expose 
private String city; 

/** 
* 
* @return 
* The id 
*/ 
public Integer getId() { 
return id; 
} 

/** 
* 
* @param id 
* The id 
*/ 
public void setId(Integer id) { 
this.id = id; 
} 

/** 
* 
* @return 
* The type 
*/ 
public Integer getType() { 
return type; 
} 

/** 
* 
* @param type 
* The type 
*/ 
public void setType(Integer type) { 
this.type = type; 
} 

/** 
* 
* @return 
* The city 
*/ 
public String getCity() { 
return city; 
} 

/** 
* 
* @param city 
* The city 
*/ 
public void setCity(String city) { 
this.city = city; 
} 

} 
+0

オブジェクトには4つのタイプがあり、対処方法 – rainash

+0

モデルクラスを変更し、オブジェクトを「オブジェクト」クラスのリストとして定義することができます。私は別のクラスオブジェクトを作成し、ゲッタとセッタを別々に定義します。しかし、はい私は配列としてのオブジェクトの値は、オブジェクトとしてオブジェクトの値とは異なる名前を持つ必要がありますと考えて –

0

、私は以下のソリューションを提案:あなたのモデルクラスは次のようになりますジェネリックJsonElementのgson(あなたのプロジェクトでそれをCtrl-Bを押すか、hereを参照のうえで、このクラスの詳細情報を見つけることができます)

public class CustomJson { 
    private int type; 
    private JsonElement object; 
} 
あなたは JSONObjectJSONArrayに変換したい場合 com.google.gson.JsonElementは、 JsonObject(ない JSONObject)または JsonArray(ない JSONArray)可能性があるので

Gson gson = new Gson(); 
CustomJson[] customJson = gson.fromJson(jsonString, CustomJson[].class); 

を:解析するGsonを使用して活動

その後、ここに私がテストしている私のプロジェクトでlogcatの結果である

 if (customJson!= null && customJson.length > 0) { 
      for (CustomJson aCustomJson : customJson) { 
       JsonElement jsonElement = aCustomJson.object; 
       if (jsonElement instanceof JsonObject) { 
        try { 
         JSONObject jsonObject = new JSONObject(jsonElement.toString()); 
         Log.i(LOG_TAG, jsonObject.toString()); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } else if (jsonElement instanceof JsonArray) { 
        try { 
         JSONArray jsonArray = new JSONArray(jsonElement.toString()); 
         Log.i(LOG_TAG, jsonArray.toString()); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 

::、次のコードを使用

09-08 15:41:48.024 6202-6202/com.example.jsonparse I/JSONParse﹕ {"title1":"title1","title2":"title2"} 
09-08 15:41:51.458 6202-6202/com.example.jsonparse I/JSONParse﹕ ["string","string","string"] 
09-08 15:41:51.458 6202-6202/com.example.jsonparse I/JSONParse﹕ [{"text":"text","url":"url","height":600,"width":600},{"text":"text","url":"url","height":600,"width":600}] 
09-08 15:41:51.458 6202-6202/com.example.jsonparse I/JSONParse﹕ {"type":1,"id":337203,"city":"1"} 

1

これは、元のポスターのために少し遅れかもしれないが、うまくいけば、それは他の誰かを助けます。

GsonAndroidに使用しています。 私は誰もがカスタムクラスと長い道のりのソリューションを使用しているのを見ました。 鉱山は基本です。

私は多くの異なるオブジェクト型(私のデータベースのためのモデル)のArrayListを持っています - プロフィールはそれらの一つです。

{"profile": 
    {"name":"Josh", 
    "position":"Programmer", 
    "profile_id":1, 
    "profile_image_id":10, 
    "user_id":1472934469 
    }, 
"user": 
    {"email":"[email protected]", 
    "phone_numbers":[], 
    "user_id":1, 
    "user_type_id":1 
    }, 
"follower": 
    {"follower_id":3, 
    "following_date":1.4729345E9, 
    "referred_by_id":2, 
    "user_from_id":1, 
    "user_to_id":2 
    }, 
"media": 
    {"link":"uploads/profiles/profile-photos/originals/1-G9FSkRCzikP4QFY.png", 
    "media_description":"", 
    "media_id":10, 
    "media_name":"", 
    "media_slug":"", 
    "medium_link":"uploads/profiles/profile-photos/thumbs-medium/1-G9FSkRCzikP4QFY.png", 
    "thumbnail_link":"uploads/profiles/profile-photos/thumbs-small/1-G9FSkRCzikP4QFY.png", 
    "uploader_id":1 
    } 
} 

は、今私はGsonオブジェクトの作成:私は返すmContactList.get(i)を使用してアイテム入手カスタムクラスを作成するのではなく、今

Gson gson = new Gson(); 
// this creates the JSON string you see above with all of the objects 
String str_obj = new Gson().toJson(mContactList.get(i)); 

を - ちょうど次のコードを使用してJsonObjectとしてそれを通過:

JsonObject obj = gson.fromJson(str_obj, JsonObject.class); 

そして今、あなたはそうのようなオブジェクトを呼び出すことができます。

JsonObject profile = obj.getAsJsonObject("profile"); 
関連する問題