我该如何反序列化阵列谷歌-GSON内部数组 [英] How can I deserialize Array inside of Array google-gson

查看:103
本文介绍了我该如何反序列化阵列谷歌-GSON内部数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JSON这样的:

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

正如你所看到的,我有阵内阵。我怎么能这样反序列化JSON结构成一个对象使用的谷歌GSON 在Android库(的 HTTPS://$c$c.google.com/p/google-gson/

As you can see, I have array inside of array. How can I deserialize such JSON structure into an object using google-gson library on Android (https://code.google.com/p/google-gson/)?

推荐答案

JSON格式之后,我们得到了这样的事情:

After Json format we got something like this:

为MyObject

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

这篇关于我该如何反序列化阵列谷歌-GSON内部数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆