1

I have a java code like this:

JSONObject jsonObj = new JSONObject(output);
JSONArray json_response = jsonObj.getJSONArray("DataList");
for (int i = 0; i < json_response.length(); i++) {
    JSONObject jsonobject = json_response.getJSONObject(i);
    Tblshop tblshop = new Tblshop();
    tblshop.setSHID(jsonobject.getInt("SHID"));
    tblshop.setShimagename(jsonobject.getString("ShImgName"));
    tblshop.setShname(jsonobject.getString("ShName"));
    tblshop.setShoff(jsonobject.getInt("ShOff"));
    tblshop.setShstate(jsonobject.getInt("ShState"));
    tblshop.setShstar(jsonobject.getInt("ShStar"));
    tblshop.setShtask(jsonobject.getInt("ShTask"));  
    tblshop.setShvarification(jsonobject.getInt("ShVarification"));
    tblshopDao.insertOrReplace(tblshop);
}

But I don't want to use a set for One by one field and I want to do that with a loop or something and just take Model(Structure name) and that loop does this with the field names.

What can I do about this (The model Field names are exactly like Json Array field names).

Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
Sajad Asadi
  • 97
  • 2
  • 14

1 Answers1

4

If you have modeled the JSON array properly, you can use the code below to change your JSON array to your object:

public static <T> T fromJson(String jsonString, Class<T> classType) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.registerModule(new JodaModule());

    try {
        return mapper.readValue(jsonString, classType);
    } catch(IOException var4) {
        var4.printStackTrace();
        return null;
    }
}

For example: JSON array like:

["name":"alireza" , "city":"tehran"]

Create a class like:

public class MyClass {

    private String name;
    private String city;

    public void setName(String name) {
        this.name = name;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

Then you can make an object out of your JSON array like:

MyClass obj = fromJson(yourJSON, MyClass.class);
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
A.Shaheri
  • 450
  • 4
  • 13