开发者

Json to string array using Gson

开发者 https://www.devze.com 2023-03-20 11:37 出处:网络
I\'m having troubles with the deserialization of this Json: [{\"categorium\": {\"created_at\":\"2011-06-09T08:57:41Z\",\"c1\":\"rete stradale\",\"updated_at\":\"2011-06-09T08:57:41Z\",\"id\":1}},

I'm having troubles with the deserialization of this 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}}
]

How can I extrapolate all "c1" attributes, so I can return a string array of them?

*UPDATE: SOLUTION *

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&l开发者_运维知识库t;cArray.length; i++) {
          c1Array[i] = cArray[i].c1;
      }

    return c1Array;


 }
}

Categorium class:

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;
    }

}


To deserialize an array use this code:

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

Then to get all c1's:

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

精彩评论

暂无评论...
验证码 换一张
取 消