Convert string to JSON array

JavaAndroidJson

Java Problem Overview


I have the following string of a JSON from a web service and am trying to convert this to a JSONarray

{
    "locations": [
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        },
        {
            "lat": "23.053",
            "long": "72.629",
            "location": "ABC",
            "address": "DEF",
            "city": "Ahmedabad",
            "state": "Gujrat",
            "phonenumber": "1234567"
        }
    ]
}

I validated this String online, it seems to be correct. Now I am using the following code in android development to utilise

JSONArray jsonArray = new JSONArray(readlocationFeed);

This throws exception a type mismatch Exception.

Java Solutions


Solution 1 - Java

Here you get JSONObject so change this line:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

with following:

JSONObject jsnobject = new JSONObject(readlocationFeed);

and after

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}

Solution 2 - Java

Input String

[   {      "userName": "sandeep",      "age": 30   },    {      "userName": "vivan",      "age": 5   }]

Simple Way to Convert String to JSON

public class Test
{

	public static void main(String[] args) throws JSONException
	{
		String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}]  ";
		JSONArray jsonArr = new JSONArray(data);

		for (int i = 0; i < jsonArr.length(); i++)
		{
			JSONObject jsonObj = jsonArr.getJSONObject(i);

			System.out.println(jsonObj);
		}

	}
}

Output

{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

Solution 3 - Java

Using json lib:-

String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);

Using GSON lib:-

Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

Solution 4 - Java

you will need to convert given string to JSONObject instead of JSONArray because current String contain JsonObject as root element instead of JsonArray :

JSONObject jsonObject = new JSONObject(readlocationFeed);

Solution 5 - Java

String b = "[" + readlocationFeed + "]";
JSONArray jsonArray1 = new JSONArray(b);
jsonarray_length1 = jsonArray1.length();
for (int i = 0; i < jsonarray_length1; i++) {

}

or convert it in JSONOBJECT

JSONObject jsonobj = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsonobj.getJSONArray("locations");

Solution 6 - Java

Try this piece of code:

try {		 
	Log.e("log_tag", "Error in convert String" + result.toString());
	JSONObject json_data = new JSONObject(result);

	String status = json_data.getString("Status");
	{
		String data = json_data.getString("locations");
		JSONArray json_data1 = new JSONArray(data);
		for (int i = 0; i < json_data1.length(); i++) {
			json_data = json_data1.getJSONObject(i);
			
			String lat = json_data.getString("lat");
			String lng = json_data.getString("long");
		}
    }
}

Solution 7 - Java

if the response is like this

"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"

you can parse like this

JSONObject jobj=new JSONObject(response);
		String c = jobj.getString("GetDataResult");			
		JSONArray jArray = new JSONArray(c);
		deviceId=jArray.getJSONObject(0).getString("DeviceID");

here the JsonArray size is 1.Otherwise you should use for loop for getting values.

Solution 8 - Java

You can do the following:

JSONArray jsonArray = jsnobject.getJSONArray("locations");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
}

Solution 9 - Java

It's a very simple way to convert:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;


class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;

public String getUsername() {
	return username;
}

public void setUsername(String username) {
	this.username = username;
}

public String getEmail() {
	return email;
}

public void setEmail(String email) {
	this.email = email;
}

public Integer getCredits() {
	return credits;
}

public void setCredits(Integer credits) {
	this.credits = credits;
}

public String getTwitter_username() {
	return twitter_username;
}

public void setTwitter_username(String twitter_username) {
	this.twitter_username = twitter_username;
}

@Override
public String toString() {
	return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}

}

/*
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
	Gson gson = new Gson();
	try {
		BufferedReader br = new BufferedReader(new FileReader(
				"C:\\Temp\\jsonFileArr.json"));
		JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			JsonElement str = jsonArray.get(i);
			Usuario obj = gson.fromJson(str, Usuario.class);
			System.out.println(obj);
			System.out.println(str);
			System.out.println("-------");
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

}

Solution 10 - Java

If having following JSON from web service, Json Array as a response :

       [3]
 0:  {
 id: 2
 name: "a561137"
 password: "test"
 firstName: "abhishek"
 lastName: "ringsia"
 organization: "bbb"
    }-
1:  {
 id: 3
 name: "a561023"
 password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
 }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
  firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .

      List<User> list = new ArrayList<User>();
	  JSONArray jsonArr = new JSONArray(response);
	 
	
	  for (int i = 0; i < jsonArr.length(); i++) {
		JSONObject jsonObj = jsonArr.getJSONObject(i);
		 ObjectMapper mapper = new ObjectMapper();
	    User usr = mapper.readValue(jsonObj.toString(), User.class);      
		list.add(usr);
	
	}

mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshish KasmaView Question on Stackoverflow
Solution 1 - JavakyogsView Answer on Stackoverflow
Solution 2 - JavaSandeep BhardwajView Answer on Stackoverflow
Solution 3 - JavaAravind CheekkallurView Answer on Stackoverflow
Solution 4 - Javaρяσѕρєя KView Answer on Stackoverflow
Solution 5 - JavaFurqiView Answer on Stackoverflow
Solution 6 - JavaNirav RanparaView Answer on Stackoverflow
Solution 7 - JavaSanuView Answer on Stackoverflow
Solution 8 - JavaJonathan Nolasco BarrientosView Answer on Stackoverflow
Solution 9 - JavaMarlon Leite de AlbuquerqueView Answer on Stackoverflow
Solution 10 - Javaabhishek ringsiaView Answer on Stackoverflow