Best practice for getting JSON and converting it to an object

I get a JSON string in java and I want to convert it to an object representing a 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 a simpler way, such as the binder ins asp.net mvc model?

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

+4
source share
3 answers

You can use the Google Gson library to easily convert 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
}
+4
source

json , Gson . :.

    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/

( webservice) , @SerializedName. ( Serializable)

+2

You can see the streaming parser, for example, GSON / Jackson, etc.

0
source

Source: https://habr.com/ru/post/1530933/


All Articles