how to get data from JSONObject - java

This is the JSON i get access to:
[{"Nombre":"Craic Irish Pub","Descripcion":"Pub estilo Irlandes","Telefono":"234234","SitioWeb":"","Horario":"Viernes - Sabados 17:00- 24:00","Parqueo":"No","Ubicacion":"San Jose","Reservas":"Si","_id":"5449b3334d50a38754000003","__v":0}, {"Nombre":"TicoPub","Descripcion":"Pub Moderno","Telefono":"34534534","SitioWeb":"ticopub.com","Horario":"Viernes - Sabados 17:00- 24:00","Parqueo":"Si","Ubicacion":"Lindora","Reservas":"Si","_id":"5449b3cd4d50a38754000006","__v":0}]
i can read it and save it as a JSONObject (named json) however i can't do this:
JSONArray values = json.getJSONArray(0)
how can i access it?

You definitely cannot store that JSON in a JSONObject, since it is NOT a JSON object. It is a JSON array. So use a JSONArray to store it.

Based on what you typed I assumed you're using json.org's library. As Sotirios pointed out, whenever you have '[]' in a json string that means you're using array. You must first create a Json array and then you can access the individual object (you have two of them). See below:
String jsonString = "[{'Nombre':'Craic Irish Pub','Descripcion':'Pub estilo " +
" Irlandes','Telefono':'234234','SitioWeb':'','Horario':'Viernes - Sabados 17:00- 24:00'," +
"'Parqueo':'No','Ubicacion':'San Jose','Reservas':'Si','_id':'5449b3334d50a38754000003','__v':0}, " +
" {'Nombre':'TicoPub','Descripcion':'Pub Moderno','Telefono':'34534534','SitioWeb':'ticopub.com','Horario':'Viernes - Sabados 17:00- 24:00'," +
"'Parqueo':'Si','Ubicacion':'Lindora','Reservas':'Si','_id':'5449b3cd4d50a38754000006','__v':0}]";
JSONArray array = new JSONArray(jsonString);
JSONObject obj = array.getJSONObject(0);
String nombre = obj.getString("Nombre");
System.out.println(nombre); //prints 'Craic Irish Pub'

Related

Best way to manipulate the string inside a JSONArray

I have a JSON array built from objects added to a JSON object which I would like to slightly modify to get in the desired format.
Code Snippet:
JSONObject jobj = new JSONObject();
JSONArray jarr = new JSONArray();
Object col = "name";
Object num = 3;
Object val = "{set:" + num + "}";
jobj.put(col, val);
jarr.add(jobj);
System.out.println("what is jarr: " +jarr);
The output for the above code is the following:
what is jarr: [{"name":"{set:3}"}]
And, I would like the jarr array to be in this way instead:
[{"name”:{“set”:”3”}}]
Using a \" or '"' is including that character as well. Also, I am not able to get rid of the enclosing double quotes for the value of name. It is always recognizing it as a string and adding the enclosing double quotes for {set:3}.
Is there a good way to get the jarr in the above-mentioned format?

How to get the values from keys in nested objects using only json-simple

I want to get only a specific value out of all the nested objects. In the application I just need the msg 3 which is inside another object messages.
I have tried it using JSONObject but it is not working for nested object. However It is working with just a single object means root object .
INPUT - {"name":"lola","messages":{"msg 1":"msg 2","msg 3":"msg 4"},"age":22}
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
Object name = json.get("messages");
System.out.println(name);
JSONObject messageObject = (JSONObject) json.get("messages");
System.out.println(employeeObject);
//Get employee first name
String msg= (String) messageObject.get("msg3");
System.out.println(msg);
The Output:
{"msg 3":"msg 4","msg 1":"msg 2"}
{"msg 3":"msg 4","msg 1":"msg 2"}
null
The last nested object is not fetching in any way. Another thing is that the normal print of the string as a JSONObject gets changed. like the msg3 came before msg1.
In place of null - msg4 should be there.
Thanks in advance.
You are missing a space between "msg" and "3". By the way - you can do this easier, as such.
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
System.out.println(json.get("message").get("msg 3"));

Decoding JSON in Java

im really new to java through Eclipse android, and im trying to decode this line of JSON
{"FullName":"bobby Bloggs"}
But when i try to put it into an array through
JSONObject jsonObject = new JSONObject(httpData);
JSONObject feedObject = jsonObject.getJSONObject("FullName");
I hit an exception of
org.json.JSONException: Value bobby Bloggs at FullName of type java.lang.String cannot be converted to JSONObject
Thanks
You are trying to read a String, since {} within the JSON means it is an object. Everything between "" means it's a string. true/false a boolean (getBoolean) and numbers are an Integer (getInteger). Since you want the String you need to use.
String FullName = JSONObject.getString("FullName");
You are trying to get JSONObject out of JSON Object i.e jsonObject.getJSONObject("FullName"); and again assigning to JSONObject.
As suggested by Emanuel use getString to get the data of "FullName" as and assign to a String.
JSONObject jsonObj = new JSONObject(httpData);
String FullName = jsonObj.getString("FullName");
will work.

how to get the name of json object from my json array

I am trying to get the name of my json key from my jsonarray but not able to take in java.
[{"ParamName":"param1","DefaultValue":"","Hidden":"Hidden","LinkedParameter":"city"}]
I just want to take name of key like i only want to take "ParamName" and need to check
if (ParamName == "ParamName") {
Then do this.
}
You can convert this to JSON object.
JSONArray json = (JSONArray)new JSONParser().parse("[{\"ParamName\":\"param1\",
\"DefaultValue\":\"\",\"Hidden\":\"Hidden\",\"LinkedParameter\":\"city\"}]");
JSONObject obj= (JSONObject) json.get(0);
if("ParamName".equals(obj.get("ParamName"))){
}

converting from String to JSONArray or JSONObject in Java

I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.

Categories