1

Is there efficient way to convert org.json.JSONObject to POJO model using GSON ? (At the moment U thought to do like

Gson g=new Gson();
g.fromJson(json.toString(), PersonModel.class);

json is JSONObject). I am using volley and in response I get instance of JSONObject and I can parse like on http://www.kpbird.com/2013/05/volley-easy-fast-networking-for-android.html but I have complex structure in models like nested lists and I would like to avoid manual extracting of data from json.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
PaolaJ.
  • 10,872
  • 22
  • 73
  • 111
  • Is the snippet you posted failing? – Sotirios Delimanolis Sep 03 '13 at 20:12
  • @SotiriosDelimanolis I don't think so, I just think that there is maybe size cosntaring for String in Java so if object is big I can be in problem ( If I can convert JSONObject to stream) – PaolaJ. Sep 03 '13 at 20:22
  • See http://stackoverflow.com/questions/816142/strings-maximum-length-in-java-calling-length-method for maximum string length. If you are on a phone and processing an object graph that turns into a 2GB String then I suspect you will have bigger problems earlier in the pipeline. – digitaljoel Sep 03 '13 at 21:13

1 Answers1

0

First, sorry for bumping an old question.

I was asking myself this same question and found this example in the Android Volley section called implementing custom requests in the Android Developer site.

@Override
protected Response<T> parseNetworkResponse(
        NetworkResponse response) {
    try {
        String json = new String(response.data,
        HttpHeaderParser.parseCharset(response.headers));
    return Response.success(gson.fromJson(json, clazz),
    HttpHeaderParser.parseCacheHeaders(response));
    }
    // handle errors
...
}

I would just use the StringRequest and use GSON on the response callback, it should be faster than getting a JSONObject and converting it to String prior to calling GSON. For what I see in the JSONObject javadoc there's no way to create an instance from a byte[], so probably the HTTP response in bytes is converted to String, then to JSONObject, and then you convert it to String again. By using StringRequest we can skip the last 2 steps.

momo
  • 3,404
  • 6
  • 37
  • 66