【问题标题】:Json to string array using Gson使用 Gson 将 Json 转换为字符串数组
【发布时间】:2011-07-13 10:35:30
【问题描述】:

我在反序列化这个 Json 时遇到问题:

[{"categorium":
     {"created_at":"2011-06-09T08:57:41Z","c1":"rete stradale","updated_at":"2011-06-09T08:57:41Z","id":1}},
     {"categorium":{"created_at":"2011-06-09T13:50:29Z","c1":"servizi pubblici","updated_at":"2011-06-09T13:50:29Z","id":2}},
     {"categorium":{"created_at":"2011-06-09T13:50:37Z","c1":"illuminazione","updated_at":"2011-06-09T13:50:37Z","id":3}},
     {"categorium":{"created_at":"2011-06-09T13:50:46Z","c1":"inquinamento","updated_at":"2011-06-09T13:50:46Z","id":4}}
]

如何推断所有“c1”属性,以便返回它们的字符串数组?

*更新:解决方案 *

public class getElements  {

String [] getEl (String url) throws ClientProtocolException, IOException {

    Categoria c = null;
    Categoria[] cArray = null;
    String [] c1Array = null;
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://10.0.2.2:3000/"+url);

    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    String stringa = "{\"categorium\":{\"created_at\":\"2011-06-09T08:57:41Z\",\"c1\":\"rete stradale\",\"updated_at\":\"2011-06-09T08:57:41Z\",\"id\":1}}";

     Gson json=new Gson();
      try{
          cArray=json.fromJson(stringa, Categoria[].class);
          Log.i("ELEMENTO", ""+cArray);
      }catch(JsonParseException e){
          Log.i("error","JsonParseException");
      }

      c1Array = new String[cArray.length];
      for (int i=0; i<cArray.length; i++) {
          c1Array[i] = cArray[i].c1;
      }

    return c1Array;


 }
}

分类类别:

public class Categoria {
    public String created_at;
    public String c1;
    public String updated_at;
    public int id;

    public Categoria() {
        this.created_at = "";
        this.c1="";
        this.updated_at = "";
        this.id = 0;
    }

}

【问题讨论】:

  • 为什么不能读取所有的 Categoria 对象,然后在一个简单的循环中手动创建 c1 元素的数组?
  • 我怎样才能阅读所有这些?使用我编写的代码,我只需要一个 c1,对吗?对了……logcat给我一个JsonParseException:“entity.toString”是获取字符串类型Json的正确方法吗?

标签: android json gson


【解决方案1】:

要反序列化数组,请使用以下代码:

Categorium[] cArray = null;
cArray = gson.fromJson(stringa, Categorium[].class);

然后获取所有c1的:

String[] c1Array = new String[cArray.length];
for (int i=0; i<cArray.length; i++) {
    c1Array[i] = cArray[i].c1;
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2012-03-05
    • 1970-01-01
    • 2021-10-04
    • 2013-05-19
    相关资源
    最近更新 更多