2015-05-27 37 views
-3

我有一个JSON对象,其中包含其他键值类型的字符串。下面是我的JSON代码:如何使用GSON解析JSON字符串?

{ 
    "objs": [ 
    { 
     "obj1": { 
     "ID1": 1, 
     "ID2": 2 
     } 
    } 
    ] 
} 

如何解析"ID1""ID2"

+0

您json的格式不正确。检查 @javaboygo后 – Bharatesh

回答

1

创建类,添加变量和标记他们为反序列化:

public class Root { 
    @SerializedName("objs") 
    public List<Obj> objects; 
} 

public class Obj { 
    @SerializedName("obj1") 
    public Obj1 obj1; 
} 

public class Obj1 { 
    @SerializedName("ID1") 
    public int ID1; 

    @SerializedName("ID2") 
    public int ID2; 
} 

然后反序列化您的JSON:

Gson gson = new Gson(); 
Root root = gson.fromJson(jsonString, Root.class); 
+0

但这里ID1和ID2是在行情。无法解析。 –

+0

什么?也许你不能,但GSON可以。这就是json的工作原理。 – ElDuderino

+0

在这种情况下,此解决方案将不起作用。我尝试删除Obj1类,并使用一个String变量(在Obj类中),但它仍然会抛出MalformedJsonException。诸如[JSONLint](http://jsonlint.com/)和[Json Validator](http://jsonformatter.curiousconcept.com/)等网站也提供相同的输出。你需要重新格式化你的Json,否则它将无法工作。 –

1

是JSON的正确的方法是:

{"objs":[ 
      {"obj1": 
        {"ID1":1,"ID2":2} 
      } 
     ] 
} 

如果你想使用GSON:

JsonElement jelement = new JsonParser().parse(jsonLine); 
JsonObject jobject = jelement.getAsJsonObject(); 
jobject = jobject.getAsJsonObject("objs"); 
JsonArray jarray = jobject.getAsJsonArray("obj1"); 
jobject = jarray.get(0).getAsJsonObject(); 
String ID1 = jobject.get("ID1").toString(); 
String ID2 = jobject.get("ID2").toString();