简体   繁体   中英

Converting Json to Pojo

I've recently decided to rewrite one of my older android applications and I can't figure out how to convert server response like this:

{
    "response": "SUCCESS",
    "data": {
        "0": {
            ... fields ... 
        },
        "1": {
            ... fields ...

        },
        ... another objects
    }
}

to regular java object (or in this case list of objects). I was previously using this method:

    JSONObject response = new JSONObject(stringResponse);
    JSONObject dataList = response.getJSONObject("data");
    int i = 0;
    while (true) {
        dataList.getJSONObject(String.valueOf(i)); // here I get wanted object
        i++;
    }

to get relevant objects and then I can put them into List, but now I'm using Retrofit library and I'm not able to find any clean solution to parse such weird object using gson and retrofit.

Thanks for any help.

Edit: What I want:

Send request using retrofit like this:

@GET("/some params")
void restCall(... another params..., Callback<Response> callback);

and then have List of objects in Response object. What I don't know is how to declare Response object, so it can convert that weird response into normal List of objects.

您周围有很多库。.我使用的一个是json-simple,您可以使用:

JSONValue.parse(String);

look into gson too! i'm using it for all my projects, serializing and deserializing to pojos is remarkably simple and customizable (if needed, most things are fine out of the box) gson

here is their first example:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  
==> json is {"value1":1,"value2":"abc"}
obj = gson.fromJson( json ); 
==> you get back the same object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM