How Do I Modify My Function To Retrieve Json Objects To A Nested Json?
Here's the json I currently use in my code : {'forceDeviceLockout':0,'canStartValue':true,'destructOnRead':[30,60,300]} I use the following function to get the json values: privat
Solution 1:
I don't know why are you making it so complicated! but see this code I wrote for you. it might give you an idea:
public void printFieldsValues(Object object){
try{
Field[] fields = object.getClass().getFields();
JSONObject jsonObject = new JSONObject();
for(Field field : fields){
jsonObject.put(field.getName(), field.get(object));
}
JSONObject newValue = new JSONObject("{\"canStartNewValue1\":true,"
+ "\"canStartroupValue\":true}");
jsonObject.put("NEWVALUE", newValue);
printJson(jsonObject);
}catch(Exception e){
e.printStackTrace();
}
}
public void printJson(JSONObject jsonObject) throws JSONException{
Iterator<String> keys = jsonObject.keys();
String key;
while(keys.hasNext()){
key = keys.next();
try{
printJson(new JSONObject(jsonObject.getString(key)));
}catch(Exception e){
Log.d("TAG", "key = " + key);
Log.d("TAG", "value = " + jsonObject.get(key).toString());
}
}
}
and in your main Object you can call it like this:
printFieldsValues(this);
Solution 2:
If those json keys are predefined we can access them like this
public class SampleModel {
public int forceDeviceLockout;
public boolean canStartValue;
public int[] destructOnRead;
public NestedModel NEWVALUE;
}
public class NestedModel {
public boolean canStartNewValue1;
public boolean canStartroupValue;
}
Gson gson = new Gson();
SampleModel sampleModel = gson.fromJson("{\"forceDeviceLockout\":0,\"canStartValue\":true,\"destructOnRead\":[30,60,300],\"NEWVALUE\":{\"canStartNewValue1\":true,\"canStartroupValue\":true}}",SampleModel.class);
Log.d("canStartNewValue : " ,sampleModel.canStartNewValue)
Log.d("canStartNewValue1 : " , sampleModel.NEWVALUE.canStartNewValue1);
Note : Need to add dependency compile 'com.google.code.gson:gson:2.8.2'
Solution 3:
If you just want to modify your current code to parse the json received you could just add
if(value instance of JSONObject){
JSONObject jsonObject = (JSONObject) value;
return jsonObject;
}
Post a Comment for "How Do I Modify My Function To Retrieve Json Objects To A Nested Json?"