JSON Exception String cannot be converted to JSON Object - java

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);

Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

Related

parse json using java (simplejson)

I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

Removing the end [ and ] from php Json result for Android Java code

My PHP code is this:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
#$row = mysql_fetch_row($userdetails) ;
while($rows=mysqli_fetch_array($userdetails)){
$status[]= array($rows['Aircraft']=>$rows['Status']);
}
#Output the JSON data
echo json_encode($status);
and gives this:
[{"A70_870":"1"},{"A70_871":"1"},{"A70_872":"1"},{"A70_873":"1"},{"A70_874":"1"},{"A70_875":"1"},{"A70_876":"2"},{"A70_877":"1"},{"A70_878":"2"},{"A70_879":"2"},{"A70_880":"2"},{"A70_881":"0"},{"A70_882":"0"},{"A70_883":"0"},{"A70_884":"0"},{"A70_885":"0"}]
The java code that reads it is this:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
n870 = jsonObject.getInt("A70_870");
n871 = jsonObject.getInt("A70_871");
n872 = jsonObject.getInt("A70_872");
n873 = jsonObject.getInt("A70_873");
n874 = jsonObject.getInt("A70_874");
n875 = jsonObject.getInt("A70_875");
n876 = jsonObject.getInt("A70_876");
n877 = jsonObject.getInt("A70_877");
n878 = jsonObject.getInt("A70_878");
n879 = jsonObject.getInt("A70_879");
n880 = jsonObject.getInt("A70_880");
n881 = jsonObject.getInt("A70_881");
n882 = jsonObject.getInt("A70_882");
n883 = jsonObject.getInt("A70_883");
n884 = jsonObject.getInt("A70_884");
n885 = jsonObject.getInt("A70_885");
When i run my android app I seem to keep getting the error:
"of type org.json.JSONArray cannot be converted into Json object"
However when I send the app dummy code without the square brackets, it seems to work fine! How do I get rid of those [ and ] brackets on the ends???
Alternatively is there a way to accept the json as it is and adapt the java to read it?
echo json_encode($status, JSON_FORCE_OBJECT);
Demo: http://codepad.viper-7.com/lrYKv6
or
echo json_encode((Object) $status);
Demo; http://codepad.viper-7.com/RPtchU
Instead of using JSonobject, use JSONArray
JSONArray array = new JSONArray(sourceString);
Later loop through the array and do the business logic.
http://www.json.org/javadoc/org/json/JSONArray.html
Maybe with this kind of json structure?
$status[$rows['Aircraft']]= $rows['Status'];
You get an JSONArray, Not Object, you could create an Object holding an array, or parsing the array.
Refering to this post
Solution #1 (Java)
How about a helper method like this:
private int getProp(String name, JSONArray arr) throws Exception {
for (int i = 0; i < arr.length(); ++i) {
JSONObject obj = arr.getJSONObject(i);
if (obj.has(name))
return obj.getInt(name);
}
throw new Exception("Key not found");
}
Then you could use it like:
JSONArray jsonArray = new JSONArray(result); // note the *JSONArray* vs your *JSONObject*
n870 = getProp("A70_870", jsonArray);
n871 = getProp("A70_871", jsonArray);
...
Note I haven't tested this code, so you may need to make some changes...
Alternate solution (PHP)
It's been awhile since I've worked with PHP, but you might be able to leave your Java code intact and change your PHP int the while-loop body to:
$status[$rows['Aircraft']] = $rows['Status'];

Parsing JSON server response into JSON Array

I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need

how to use json in java for 10 datas

hello
i have an some 10 datas from db with attribute same attribute name
JSONObject json = new JSONObject();
json.put("text",value1);
json.put("title",value2);
json.put("url",value3);
i use this above code i am getting similar to this
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
while i parse it in php i am getting an null value i dont know y .. can you tell me where i am wrong...
your output should be something like this to be parsable
[{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}]
and for this you should be using JSONArray.
Basically you will have to create a JSON Array to hold your 10 datas, like so:
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 10; i++) {
JSONObject json = new JSONObject();
json.put("text",value1);
json.put("title",value2);
json.put("url",value3);
jsonArray.put(json);
}
Output, See Bala R's response.

Categories

Resources