To decode, pass a JSON-formatted string to the JSONObject constructor. The resulting object will contain the parsed data.
If the root is an OBJECT, the data is stored in a public ArrayList called list, with corresponding keys stored in a keys list. If the root is an ARRAY, data is stored directly in list.
Recursive Traversal Pattern:
To process unknown JSON structures, use a recursive function that switches on the obj.type property (e.g., OBJECT, ARRAY, STRING, NUMBER, BOOL, NULL).
string encodedString = "{\"field1\": 0.5,\"field2\": \"sampletext\",\"field3\": [1,2,3]}";
JSONObject j = new JSONObject(encodedString);
void accessData(JSONObject obj){
switch(obj.type){
case JSONObject.Type.OBJECT:
for(int i = 0; i < obj.list.Count; i++){
string key = (string)obj.keys[i];
JSONObject child = (JSONObject)obj.list[i];
accessData(child);
}
break;
case JSONObject.Type.ARRAY:
foreach(JSONObject child in obj.list){
accessData(child);
}
break;
case JSONObject.Type.STRING:
Debug.Log(obj.str);
break;
case JSONObject.Type.NUMBER:
Debug.Log(obj.n);
break;
case JSONObject.Type.BOOL:
Debug.Log(obj.b);
break;
case JSONObject.Type.NULL:
Debug.Log("NULL");
break;
}
}