JSONObject for JSONArray

I need help here. I am still new to Android developer.

Here is sample data

strAPI_TERMINAL= "{ 'terminal': { 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' }}" 

I need to parse the data of this object in a JSONArray

Here is what I did ...

 JSONObject jsonObject = new JSONObject(strAPI_TERMINAL); JSONArray terminal_array = new JSONArray(); JSONArray t_array = terminal_array.put(jsonObject); 

When I exit the data ... yes, it was an array parsing, like this

t_array[{"terminal":{"fmt_id":"fmt0002","id":2,"terminal_type":"multiple"}]

But when I want to use it to get "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"} 

Someone please help me ???

thanks for any help ...

+1
source share
3 answers

Try to parse JSON as shown 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 helps you.

thanks

+6
source

As Josnihin said, a β€œterminal” is a JSON object. If you want this to be an array, you need to do this first (pay attention to the brackets of the array):

 strAPI_TERMINAL= "{ 'terminal': [{ 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' }]}" 

Are you really just trying to iterate over keys in a terminal object? If so, you might want to check out this post: How to iterate over a JSONObject?

+1
source

According to your code't_array 'there is a JSONObject array. To access each element in 't_array', you will need to get each element as a JSONObject, and then access the values ​​of that JSONObject.

The value of 'terminal' is a json object that you cannot convert to a json array that way.

To access the terminal value, follow these steps:

 t_array.getJSONObject(i).getJSONObject("terminal"); 

The above code will return the following as a JSONObject

 { 'id': 2, 'fmt_id': 'fmt0002', 'terminal_type': 'multiple' } 
0
source

Source: https://habr.com/ru/post/1241547/


All Articles