I have this JSON coming from one of our REST service:
[
"{\"category_name\":[\"Industry Components\"],\"categoryId\":[1]}",
"{\"category_name\":[\"Business Components\"],\"categoryId\":[2]}",
"{\"category_name\":[\"Utilities\"],\"categoryId\":[3]}",
"{\"category_name\":[\"Tools\"],\"categoryId\":[4]}
]
I am using java-json.jar to parse this JSON, this is the simple snippet where I am trying to pass above JSON string:
JSONObject jsonObject = new JSONObject(jsonStr);
But I am getting below exception:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
First I assumed it's because of [ and ] characters in JSON and I tried to replace as below:
String replacedStr = jsonStr.replaceAll("\\[", "").replaceAll("\\]", "")
But even then I am getting same exception. Can anyone please guide me to know what I am doing wrong?
I suppose that you should use not JSONObject, but JSONArray
JSON Object follows the following Structure:
{
"array": [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
}
]
}
JSON Array follows the following Structure:
[
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
]
instead
JSONObject jsonObject = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and may be read about Gson is a nice library for parsing and work with json
If you get JSONObject text must begin with '{' exception.
Then first off all check what did u pass to the JSONObject constructor.
You should pass the right json.txt file.So make sure what are u passing to jsonobject.
String request = FileUtils.readFileToString(new File("/home/achaure/Downloads/Amol/KountRestTest/Documents/request.txt"));
JSONObject jsonObject = new JSONObject(request);
Related
I would like to read the "messages" element that can come at any level of the Json structure.
Sample Json
{
"Order": {
"array": [
{
"messages": "value"
},{
"element1":"value",
"element2":"value"
}
],
"Object1":"value",
"Object2":{
"element1":"value",
"messages":"value"
}
}
}
Can someone please suggest how can i read messages section in java. Here this particular element can come at level or any object in the json.
You can use JSONObject to play with any level but you should know the element key of the level .
import org.json.JSONObject
JSONObject jsonObj = new JSONObject( "{\"extensions\":{\"car\":{\"color\":\"blue\",\"ageInYears\":10},\"favoriteNumber\":3.14159265359,\"isLucky\":true}}");
jsonObj.put("child1Key1", "someValue");
JSONArray jsonArray = new JSONArray();
System.out.println("jsonObj"+jsonObj);
jsonObj.remove("child1Key1" );
System.out.println("after adding jsonObj"+jsonObj);
jsonObj
.getJSONObject("extensions")
.getJSONObject("car").put("ageInYears","100");
System.out.println("after update jsonObj"+jsonObj);
System.out.println("after remove "+jsonObj
.getJSONObject("extensions")
.getJSONObject("car").remove("ageInYears"));;
System.out.println("after remove jsonObj"+jsonObj);
System.out.println("after remove "+jsonObj
.getJSONObject("extensions").remove("isLucky"));
//.getJSONObject("car").remove("ageInYears"));;
System.out.println("after remove-1 jsonObj"+jsonObj);
This question already has an answer here:
org.json.JSONException: JSONObject["address"] is not a JSONArray
(1 answer)
Closed 5 years ago.
Using this code to call steam api. Parsing json gives me some problems. I manage to print the json in the console, accessing furhter data fails. Here is my code:
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response")); >>> (1)
int out = json.getJSONObject("players").getInt("steamid");
System.out.println(out);
Exception in thread "main" org.json.JSONException: JSONObject["players"] not found.
{
"response": {
"players": [
{
"steamid": "XXXXX",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "XXXXX",
"lastlogoff": 123123,
"profileurl": "http://steamcommunity.com/id/XXX/",
"avatar": "XXXXX",
"avatarmedium": "XXXX",
"avatarfull": "XXXXX",
"personastate": 1,
"primaryclanid": "XXX",
"timecreated": XXX,
"personastateflags": 0,
"gameextrainfo": "Tom Clancy's Rainbow Six Siege",
"gameid": "359550"
}
]
}
}
You just need to understand the difference between JSONObject structure and JSONArray structure
The JSONObject will starts with "{", and JSONArray starts with "[".
I just noticed your mistake, you didnt assign json.get("response") to any variable.
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response"));
JSONObject playersJson=json.get("response");
int out = playersJson.getJSONArray("players").getJSONObject(0).getInt("steamid");
So try changing your code as above.
Your problem is that players is not a JSONObject, it's a JSONArray which contains JSONObjects. In this case, players contains one JSONObject, so you need to access that object first using players[0]:
int out = json.getJSONArray("players")[0].getInt("steamid");
Iam parsing a json using org.json in java . My json list like:
[ {
"id": "f187b01b145c4171b66d4a2ecabb8f44"
},
{
"id": "a5e66b7462e24924a03e89f0619a2398"
},
{
"id": "2fb3627360db4ab78a0b3f27527b1983"
} ]
I fetch data from the java code :
JSONObject json = new JSONObject(response.getEntity(String.class));
Jobs[] obj = new Gson().fromJson(json.toString(), Jobs[].class);
System.out.println(obj.toString());
But it gives an exception :
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.<init>(JSONObject.java:197)
at org.json.JSONObject.<init>(JSONObject.java:324)
at br.usp.icmc.teste.ConnectionRestClient.getSaucelabsGetJobs(ConnectionRestClient.java:80)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)
why it did not recognized as JSONArray ? Where am I wrong ?
U can try with below code. There are many ways to do it, below is one of the way
JSONArray jsonArray = new JSONArray(response.getEntity(String.class));
for(int i =0; i< jsonArray.length(); i++){
if(jsonArray.get(i) instanceof JSONObject){
JSONObject jsnObj = (JSONObject)jsonArray.get(i);
String finalValue = (String)jsnObj.get("id");
}
}
I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?
Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...
I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.
Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()