Zapnologica
Zapnologica

Reputation: 22556

Best practice to receive JSON and convert it to an object

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?

Upvotes: 4

Views: 4256

Answers (3)

Purushotham
Purushotham

Reputation: 3820

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
}

Upvotes: 4

Pararth
Pararth

Reputation: 8134

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)

Upvotes: 2

Vaibhav Ajay Gupta
Vaibhav Ajay Gupta

Reputation: 473

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

Upvotes: 0

Related Questions