I was wondering if there is a way to get a string from JSON in Java like there is in PHP:
<?php
$json = #file_get_contents('example');
$decoded_json = json_decode($json);
echo $decoded_json->{"something"} ;
?>
I have currently tried:
String input = "[{"minecraft.net":"green"},{"session.minecraft.net":"green"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"green"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"}]";
String wanted = "minecraft.net";
JSONObject json = new JSONObject(input);
String out = json.getString(wanted);
System.out.println(out);
However, it gives me this error:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
Thanks!
It's because your String is not a valid JSON object but a valid JSON array which contains objects, try to use JSONArray instead then you can query around this array for your desired object
You forgot to add \" when a double quote is inside another double quote
Related
I have the following text which is returned by an API that I call:
{"identified_faces_names": "[\"omar\", \"elhoussinep\"]"}
when I pass this text to JSONParse to parse it, it give me the following exception:
Exception in thread "main" Unexpected character (o) at position 0.
Code used to parse the text to json:
String s = new String("{\"identified_faces_names\": \" [\"omar\",\"elhoussinep\"]\"}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
Did you definitely mean to enclose ["omar", "elhoussinep"] in quotes? Is that definitely intended to be a String value containing string quotes? Or is it intended to be an array of strings?
If identified_faces_names is intended to be an array of strings then the valid JSON is:
{
"identified_faces_names": [
"omar",
"elhoussinep"
]
}
This is parseable, without error, like so:
String s = new String("{\"identified_faces_names\": [\"omar\",\"elhoussinep\"]}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
If identified_faces_names is intended to be a String containing quotes you must escape the quotes inside the string. The valid JSON is:
{
"identified_faces_names": "[\\\"omar\\\",\\\"elhoussinep\\\"]"
}
This is parseable, without error, like so:
String s = new String("{\"identified_faces_names\": \" [\\\"omar\\\",\\\"elhoussinep\\\"]\"}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
So, in summary, I'd suggest revisiting the JSON to determine whether it is an array of strings or a string which contains quotes, if the latter then you have to escape those quotes.
FWIW, you can use JSONLint to check whether the JSON is valid. Using this you can see that your original JSON ({"identified_faces_names": "["omar","elhoussinep"]"}) was not valid and that the first invalid character is the "o" in "omar" and that's deemed invalid because it follows "[" which is deemed to be a complete String.
Use this String {"identified_faces_names": [\"omar\", \"elhoussinep\"]}. It is correct and will parse.
Hi am trying to convert string json where string contains json objects and arrays both there is some thing braces or quotes missing I am not getting whats wrong happening
String companyid="14";
String userid="1002";
String projectid="378";
String scenarioid="1";
String xTable = "[{\"Label\":\"A\",\"Dimension\":\"0\"},{\"Label\":\"B\",\"Dimension\":\"10\"}]";
String yTable = "[{\"Label\":\"1\",\"Dimension\":\"0\"},{\"Label\":\"2\",\"Dimension\":\"10\"}]";
String zTable = "[{\"Label\":\"Floor1\",\"Dimension\":\"0\"},{\"Label\":\"Floor2\",\"Dimension\":\"10\"}]";
String grid="{\"grids\":{\"xaxis\":\""+xTable+"},{\"yaxis\":\""+yTable+"},{\"zaxis\":\""+zTable+"}";
String inJson="{\"grid\":\"" +grid + "\"}" ;
JSONObject user = new JSONObject(inJson);
System.out.println(user.getString("grid"));
Error:
Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at 80 [character 81 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:231)
at org.json.JSONObject.<init>(JSONObject.java:320)
at JsonExcercise.main(JsonExcercise.java:20)
its an escape sequence Problem below is the
String inJson="{\"grid\":\'" +grid + "\'}" ;
the variable grid and inJson are the wrong json format, redundant front quotation mark in the variableļ¼ and you can validate by the online web tool,the following code is correct
String companyid="14";
String userid="1002";
String projectid="378";
String scenarioid="1";
String xTable = "[{\"Label\":\"A\",\"Dimension\":\"0\"},{\"Label\":\"B\",\"Dimension\":\"10\"}]";
String yTable = "[{\"Label\":\"1\",\"Dimension\":\"0\"},{\"Label\":\"2\",\"Dimension\":\"10\"}]";
String zTable = "[{\"Label\":\"Floor1\",\"Dimension\":\"0\"},{\"Label\":\"Floor2\",\"Dimension\":\"10\"}]";
String grid="{\"grids\":[{\"xaxis\":"+xTable+"},{\"yaxis\":"+yTable+"},{\"zaxis\":"+zTable+"}]}";
String inJson="{\"companyid\":\"" +companyid + "\",\"userid\":\"" +userid + "\",\"projectid\":\"" +projectid + "\",\"scenarioid\":" +scenarioid + ",\"grid\":" +grid + "}" ;
JSONObject user = new JSONObject(inJson);
System.out.println(user.getString("companyid"));
and you could learn the json array and the json object
The error you got sais: org.json.JSONException: Expected a ',' or '}'
1st step is to check that the number of '{' and '}' match.
if you look at your code:
String grid="{\"grids\":{\"xaxis\":\""+xTable+"},{\"yaxis\":\""+yTable+"},{\"zaxis\":\""+zTable+"}";
is not balanced, it is missing a '}'
Yes, as question title. I got a single string received in android consist of 2 JSONObject.I have to do 2 different processes in PHP but both result are returned (echo) in single string result which I don't know how to seperate it.I'm using :
JSONObject json = new JSONObject(result);
String success = json.optString("success");
// "success" here shows empty in logcat. I think it doesn't get the second json object
Example of Result string:
{"username":"xx","activated":"0"}{"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
How can I do?
(btw 2nd string is Firebase Cloud Messanging result example. EDIT: I'm using PHP to send FCM, that's why the result is forced to return together with my other string result even I do not (PHP::echo) it)
Use String.split() with proper regex.
Here is the working code:
String response = "{\"username\":\"xx\",\"activated\":\"0\"}{\"multicast_id\":xxx,\"success\":0,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"xxx\"}]}";
String[] separated = response.split("\\}\\{");
String str1 = separated[0] + "}";
String str2 = "{" + separated[1];
Log.d("STRING", "String1: " + str1 + "\nString2: " + str2);
OUTPUT:
D/STRING: String1: {"username":"xx","activated":"0"}
String2: {"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
Hope this will help~
Use String.split() with proper regex.
AND
Use this website to reveal the mystery of regexp
I need to instantiate a JSONObject with a string that I receive from an external source. The string contains a datetime value, which in turn contains a colon.
When I try to create an instance of the JSONObject, I get an error, it looks like JSON does not like the colon in the middle of the date time value.
Here is a code snippet:
#Test
public void testGetDate()
{
String jsonStr = "{\"sDate\":2013-06-15T09:30:09+0000}";
try
{
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println(jsonObject.get("sDate"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
The error I get is:
org.json.JSONException: Expected a ',' or '}' at 23 [character 24 line 1]
Has anyone encountered this ? Is there some way to escape the colon?
If you surround your date/time object in double quotes, it should accept it.
This should work:
String jsonStr = "{\"sDate\":\"2013-06-15T09:30:09+0000\"}";
Strings are required to be quoted in JSON:
string
""
" chars "
Your snippet is invalid, which is why the exception is thrown. You must surround the string value with double quotes.
The more interesting issue is for cases where the string is unknown. In case the format is known then it's reasonably easy to fix. Added as a utility to org.json here.
I'm using the library org.json.
I have a string like this (quotes can't appear in field_n)
{field1=value1, field2=value2} (say it `val`)
This string is obtained from an Hashtable<String, Object>.
I create a JSONObject from that string, obtaining:
{"field1":"value1", "field2":"value2"}
The issue arises when in the value value_n quotes (or newlines and carriage return) appear.
I've tried to escape the string in this way:
value = value.replace("\\", "\\\\");
value = value.replace("\"", "\\\"");
value = value.replace("\r", "\\r");
value = value.replace("\n", "\\n");
but I always obtain the org.json.JSONException: Expected a ',' or '}' at ... [character ... line 1] when I try to create the JSONObject with:
JSONObject json = new JSONObject(val);
In order to create JSON from map, use:
new JSONObject(myMap);
Another related issue:
quotedStr = JSONObject.quote(val.trim());
will qoute all needed values as it says:
Produce a string in double quotes with backslash sequences in all the right places