4

我有这样的JSON:

{
 "Answers":
 [
  [
   {"Locale":"Ru","Name":"Name1"},
   {"Locale":"En","Name":"Name2"}
  ],
  [
   {"Locale":"Ru","Name":"Name3"},
   {"Locale":"En","Name":"Name4"}
  ]
 ]
}

如您所见,我在数组中有数组。如何使用Android 上的google-gson库(https://code.google.com/p/google-gson/)将这种 JSON 结构反序列化为对象?

4

2 回答 2

3

在 Json 格式之后,我们得到了这样的结果:

我的对象

public class MyObject {
public List<List<Part>> Answers;

public List<List<Part>> getAnswers() {
    return Answers;
  }
}

部分

public class Part {
private String Locale;
private String Name;

public String getLocale() {
    return Locale;
}
public String getName() {
    return Name;
}

}

主要的

public static void main(String[] args) {
    String str = "    {" + 
            "       \"Answers\": [[{" + 
            "           \"Locale\": \"Ru\"," + 
            "           \"Name\": \"Name1\"" + 
            "       }," + 
            "       {" + 
            "           \"Locale\": \"En\"," + 
            "           \"Name\": \"Name2\"" + 
            "       }]," + 
            "       [{" + 
            "           \"Locale\": \"Ru\"," + 
            "           \"Name\": \"Name3\"" + 
            "       }," + 
            "       {" + 
            "           \"Locale\": \"En\"," + 
            "           \"Name\": \"Name4\"" + 
            "       }]]" + 
            "    }";

    Gson gson = new Gson();

    MyObject obj  = gson.fromJson(str, MyObject.class);

    List<List<Part>> answers = obj.getAnswers();

    for(List<Part> parts : answers){
        for(Part part : parts){
            System.out.println("locale: " + part.getLocale() + "; name: " + part.getName());
        }
    }

}

输出:

locale: Ru; name: Name1
locale: En; name: Name2
locale: Ru; name: Name3
locale: En; name: Name4
于 2013-10-03T09:06:26.627 回答
1

用这个

public class MyObject extends ArrayList<ArrayList<Part>>
{
     public List<Part> Answers
}

也可以使用给定的代码反序列化它

 List<Part> Answers = Arrays.asList(gson.fromJson(json, MyObject.class));

希望对你有帮助..

于 2016-02-15T12:47:36.277 回答