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:
private Object getValueForField(Field field) {
if (runtimeConfiguration.has(field.fieldName) && field.updateFromServer) {
try {
Object value = runtimeConfiguration.get(field.fieldName);
if (value instanceof JSONArray) {
JSONArray values = (JSONArray) value;
if (values.get(0) instanceof Number) {
long[] retVals = new long[values.length()];
for (int i = 0; i < values.length(); i++) {
retVals[i] = ((Number) values.get(i)).longValue();
}
return retVals;
}
} else if (value instanceof Number) {
return ((Number) value).longValue();
} else {
return value;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return field.defaultValue;
}
Now, I have a new nested json as follows:
{"forceDeviceLockout":0,"canStartValue":true,"destructOnRead":[30,60,300],"NEWVALUE":{"canStartNewValue1":true,"canStartroupValue":true}
In the new json I am adding the nested json object : NEWVALUE which has 2 objects within itself.
I am a little weak at json so unsure how to go about modifying my code to retrieve the above individual values. Any ideas?
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);