4

I am receiving a JSON string in java, and I wish to convert it to an object that represents the string. I currently have this function:

private ArrayList<MyDevice> parseResposne(String response) {
    ArrayList<MyDevice> devices = null;
    JSONArray jsnArr = null;
    try {
        // JSONObject jObj = new JSONObject(response);
        jsnArr = new JSONArray(response);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (int i = 0; i < jsnArr.length(); i++) {
         MyDevice tmpDevice = new MyDevice(jsnArr.);
        // devices.add(tmpDevice);
    }

    return null;
}

here is my Mydevice class:

public class MyDevice {

public String name;
public int deviceId;
public String serialNo;
public String deviceType;
public boolean enabled;

public MyDevice(int deviceId, String name, String serialNo, String deviceType, boolean enabled) {
    this.deviceId = deviceId;
    this.name = name;
    this.serialNo = serialNo;
    this.deviceType = deviceType;
    this.enabled = enabled;
}
}

is there not an easier way such as the model binder ins asp.net mvc?

What is the standard / best way to convert json to an object?

Zapnologica
  • 22,170
  • 44
  • 158
  • 253

3 Answers3

4

You can use Google's Gson library for easy conversion of json to Object and vice versa.

Gson gson = new Gson();
ArrayList<MyDevice> yourArray = gson.fromJson(jsonString, new TypeToken<List<MyDevice>>(){}.getType());


public class MyDevice {

    public String name;
    public int deviceId;
    public String serialNo;
    public String deviceType;
    public boolean enabled;

   //Setters and Getters
}
Purushotham
  • 3,770
  • 29
  • 41
2

If you have a complicated json or a considerable amount of data, you may be better off using Gson to map data and your model classes. Eg.:

    Gson gson = new Gson();
    ModelClass modelClass= new ModelClass();
    modelClass= gson.fromJson(responseContent,ModelClass.class); 
//where responseContent is your jsonString
    Log.i("Web service response", ""+modelClass.toString());

https://code.google.com/p/google-gson/

For Naming discrepancies(according to the variables in webservice), can use annotations like @SerializedName. (So no need to use Serializable)

Pararth
  • 8,114
  • 4
  • 34
  • 51
  • One thing worth noting about Gson is how badly it treats invalid JSON documents - often, it'll attempt to parse them without any warning. Changing this behaviour can be quite cumbersome. – kamituel Mar 10 '14 at 09:05
  • @kamituel if the JSON is invalid, the effort of handling it would be quite similar i think, irrespective of the method :) . i'd think it is not a "parser"'s responsibility to validate the JSON though does Jackson or any other library provide invalid json handling? – Pararth Mar 10 '14 at 09:12
  • I'd prefer if parser would (at least) be able to throw an error when feeded with string which is not a JSON document. – kamituel Mar 10 '14 at 09:18
  • in case you want to try a solution, you can manually validate the json by checking if its a JSONObject or com.google.gson.JsonElement, before feeding it to a parser – Pararth Mar 10 '14 at 09:25
  • But then I'd effectively parse the same document twice. My point is that parsing library should at least warn that input wasn't valid. – kamituel Mar 10 '14 at 09:30
  • ...though does Jackson or any other library provide invalid json handling? – Pararth Mar 10 '14 at 09:32
  • @kamituel Relevant solution elsewhere, including a quick n' dirty method: http://stackoverflow.com/a/22859985 – James Daily Feb 03 '17 at 12:26
0

You can look at streaming parser such as GSON/Jackson etc.

Vaibhav Ajay Gupta
  • 463
  • 2
  • 4
  • 18