I'm new to JSON manipulation in Java and I have a String in the form of a JSON Array with several layers I need to access and put into class attributes. For example, here's my JSON object:
{"JsonObject" : [{"attributeOne":"valueOne",
"attributeTwo":"valueTwo",
"attributeThree":[{"subAttributeOne":"subValueOne",
"subAttributeTwo":"subValueTwo"}],
"attributeFour":[{"subAttributeOne":"subValueThree",
"subAttributeTwo":"subValueFour"}],
"attributeFive":"valueThree"},
{"attributeOne":"valueFour",
"attributeTwo":"valueFive",
"attributeThree":[{"subAttributeOne":"subValueFive",
"subAttributeTwo":"subValueSix"}],
"attributeFour":[{"subAttributeOne":"subValueSeven",
"subAttributeTwo":"subValueEight"}],
"attributeFive":"valueSix"}]}
Lets say I have a class called MyClass that has these attributes, how would i parse this string, knowing this is an array of n Objects, each containing "attributeOne, attributeTwo, ..., attributeFive"?
Here's what I have so far:
public MyClass[] jsonToJava (String jsonObj)
{
ArrayList<MyClass> myClassArray = new ArrayList<MyClass>();
//Somehow create a JSONArray from my jsonObj String
JSONArray jsonArr = new JSONArray(jsonObj); //Don't know if this would be correct
for(int i=0; i<jsonArr.length; i++){
MyClass myClassObject = new MyClass();
myClassObject.setAttributeOne = jsonArr[i].getString("attributeOne");
// How can I access the subAttributeOne and Two under attributeThree and Four?
// add all other values to myClassObject
myClassArray.add(myClassObject);
}
return myClassArray;
}
As you can probably tell, I'm fairly new to programming :P Thanks in advance for the help!
GSON
? its simple and fast. You just convert all your class to String and vise versa.