I need some help here. I am still new in android developer.
Here is example of the data
strAPI_TERMINAL= "{ 'terminal': { 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' }}"
I need to parse this object data to JSONArray
Here what i ve done...
JSONObject jsonObject = new JSONObject(strAPI_TERMINAL);
JSONArray terminal_array = new JSONArray();
JSONArray t_array = terminal_array.put(jsonObject);
When I Log out the data...yes it has been parse to array just like this
t_array[{"terminal":{"fmt_id":"fmt0002","id":2,"terminal_type":"multiple"}]
But When I wanna use it to get the "terminal" data using this...
JSONArray TERMINAL_JSON=new JSONArray(t_array.getJSONObject(i).getString("terminal").toString());
It says:
Error:Value {"id":2,"fmt_id":"fmt0002","terminal_type":"multiple"}
Anyone please help me???
thanks for any help...
Try out parse JSON as below:
JSONObject obj1 = new JSONObject(strAPI_TERMINAL);
try {
JSONArray result = obj1.getJSONArray("terminal");
for(int i=0;i<=result.length();i++)
{
String Id=result.getString("fmt_id");
String terminalType=result.getString("terminal_type");
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this will help you.
Thanks
As Josnidhin said, 'terminal' is a JSON Object. If you want it to be an array, you need to make it so in the first place (notice the array brackets):
strAPI_TERMINAL= "{ 'terminal': [{ 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' }]}"
Are you really just trying to iterate through the keys in the terminal object? If so, maybe you would want to check out this post: How to iterate over a JSONObject?
According to your code't_array' is an array of JSONObject. To access each item in 't_array' you will need to get each item as JSONObject and then access the values of that JSONObject.
The value of 'terminal' is a json object you cant convert it to json array just like that.
To access the value of 'terminal' do something like the following
t_array.getJSONObject(i).getJSONObject("terminal");
The above code will return the following as JSONObject
{ 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' }