2016-09-23 28 views
-2

我想使用GSON來解析類似下面的json。請指導如何使用GSON實現此操作,因爲student字段用作對象以及數組,應該如何我定義了我的pojo以及如何解析這種類型的json。具有相同名稱但不同類型的gson字段,例如對象和數組

{ 
    "school": [ 
    { 
     "student": { 
     "name": "Rose", 
     "address": "some address" 
     }, 
     "age": "15", 
     "section": "A" 
    }, 
    { 
     "student": [ 
     { 
      "name": "David", 
      "address": "Some place" 
     } 
     ], 
     "age": "14", 
     "section": "B" 
    } 
    ] 
} 

Gson gson = new Gson(); 
JSONArray jsonArray = response.getJSONArray("school"); 
Type listType = new TypeToken<ArrayList<School>>(){}.getType(); 
listSchool = gson.fromJson(jsonArray.toString(), listType); 

越來越com.google.gson.JsonSyntaxException:

java.lang.IllegalStateException:預期BEGIN_ARRAY但BEGIN_OBJECT例外

回答

0

您可以輕鬆地生成與此服務POJO的Java類:http://www.jsonschema2pojo.org/

對於你的json,它生成:

-----------------------------------com.example.School.java----------------------------------- 

package com.example; 

import java.util.ArrayList;  
import java.util.List; 
import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

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

@SerializedName("school") 
@Expose 
public List<School_> school = new ArrayList<School_>(); 

} 
-----------------------------------com.example.School_.java----------------------------------- 

package com.example; 

import java.util.ArrayList; 
import java.util.List; 
import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

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

@SerializedName("student") 
@Expose 
public List<Student> student = new ArrayList<Student>(); 
@SerializedName("age") 
@Expose 
public String age; 
@SerializedName("section") 
@Expose 
public String section; 

} 
-----------------------------------com.example.Student.java----------------------------------- 

package com.example; 

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

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

@SerializedName("name") 
@Expose 
public String name; 
@SerializedName("address") 
@Expose 
public String address; 

基本上你應該爲數組中的Student項目和學生對象使用不同的類名稱。

+0

Pojo我創建了,但是在解析時出現錯誤com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:期望BEGIN_ARRAY,但是BEGIN_OBJECT Gson gson = new Gson(); JSONArray jsonArray = response.getJSONArray(「school」); 類型listType = new TypeToken >(){}。getType(); listSchool = gson.fromJson(jsonArray.toString(),listType); – Nobdore

+0

Gson gson = new Gson(); JSONArray jsonArray = response.getJSONArray(「school」); 類型listType = new TypeToken >(){}。getType(); listSchool = gson.fromJson(jsonArray.toString(),listType); – Nobdore

相關問題