I'm performing a query on my server which returns tree information in JSON format. Below
[{"leaf": 0, "context": {}, "text": "ABC-1-6-1", "expandable": 1, "id": "1.1.2.202.ABC-1-6-1", "allowChildren": 1}]
I was having play round with json-simple library and can parse it ok using JSONParser if can get the above info in String format i.e.
String jsonString = "{\"leaf\": 0, \"context\": {}, \"text\": \"1.1.2.202.ABC-1-6-1\", \"expandable\": 1, \"id\": \"1.1.2.202.ABC-1-6-1\", \"allowChildren\": 1}";
Any help would be great!
If you want to convert JSON to java then use gson. it is very simple.
Person fromJson = new Gson().fromJson(json, Person.class);// this will convert json to java object
fromJson.setAge(15);
fromJson.setName("json");
fromJson.setEmail("email#gmail.com");
fromJson.setMob("4657576876");
json = new Gson().toJson(fromJson);// this will convert java to json string like this {"name":"json","age":15,"email":"email#gmail.com","mob":"4657576876"}
https://sites.google.com/site/gson/gson-user-guide
Refer the following link for json array convertion
serialize and deserialize json array
You have many JSON parsers for Java
Related
I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");
I have same query. My JSON is as below.
String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.
Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
Above code snippet is not Working.
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :
String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.
There are countless possibilities to check if your JSON is valid (JSON linting), here's one.
I am new To JSon and i want to search the following json string and get the required output.
String:
{"status":"Success","code":"200","message":"Retrieved Successfully","reason":null,"
"projects":
[
{
"projectName": "example",
"users":
[
{
"userName": "xyz",
"executions":
[
{
"status": "check",
"runs":
[
{
"Id": "------",
"Key": "---"
}
],
"RCount": 1
}
],
"RCount": 1
}
],
"RCount": 1
},
Like that i have many projects and now , if i give projectname and username as input i wantt to get its status as output.
Is it possible?If yes how?
You may use JSONObject for this.
JSONObject json = new JSONObject(string);
JSONArray[] projectsArray = json.getJSONArray("projects");
for(int i = 0; i < projectsArray.length; ++i)
{
String projectName = projectsArray[i].getString("projectName");
...
}
Use the same method to get the users.
You can use gson library. Using gson convert your json string to Map and then you can iterate through map to get required item
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(jsonString, type);
You can use the Google gson to map your json data structure to a Java POJOs.
Example :
You can have Projects class containing list/array of Users.
Users class containing list/array of Executions and so on.
Gson library can easily map the json to these classes as objects and you can access your data in a more elegant manner.
Here are a few references :
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
I am a newbie in Java, i'm researching how to parse json to object in java.
I have the following Json content:
{
"objects": [
{
"type": "image",
"left":0,
"top":0,
"width":787,
"height":1165,
"src":"image/16_011020002_000_bk.PNG",
"replaceable":false,
"lockObject":false
},
{
"type": "image",
"left":70,
"top":54,
"width":669,
"height":469,
"src":"image/16_011020002_000_il.PNG",
"replaceable":false,
"lockObject":false
},
{
"left":70,
"top":54,
"width":669,
"height":469,
"direction":"v",
"fontFamily":"KaitiEG4-Medium-SJIS",
"fill":"#55626C",
"text":"旧年中は大変お世話になり\nありがとうございました\n本年も相変わらずご支援のほど\nお願い申し上げます\n\n 平成二十八年 元旦",
"textAlign":"left",
"lockObject":false
},
{
"left":70,
"top":54,
"width":669,
"height":469,
"direction":"v",
"fontFamily":"LeisuEG4-Medium-SJIS",
"fill":"#55626C",
"text":"謹んで\n 初春のお慶びを\n 申し上げます",
"textAlign":"left",
"lockObject":false
}
]
}
How to design an object for this json and how to parse json to that object?
Help me this issue. Thank you!
Use some kind of JSON parser.
GSON
https://github.com/google/gson
or Jackson
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
I hope it will help you...!
use Jackson-
JSONArray objects=new JSONObject(jsondata).getJSONArray("objects");
for(int i=0;i<objects.length();i++){
JSONObject object=objects.getJSONObject(i);
System.out.println("value of left=="+object.getString("left"));
System.out.println("value of top=="+object.getString("top"));
}
As per your question its seems to be an array representing the json data of type object.
To parse the data we can use the above two parsers mentioned by d__k.
I have been using Jackson and we have a ObjectMapper class which converts the data in the specified type. We can use ObjectMapper#readValue to read the data into java object.
Kindly find more information at this link.
I'm new to JSON. I'm trying to create a JSON string in Java (org.json.JSONObject(json.jar)) which resembles like (basically a set of name-value pairs)
[{
"name": "cases",
"value": 23
}, {
"name": "revenue",
"value": 34
}, {
"name": "1D5",
"value": 56
}, {
"name": "diag",
"value": 14
}]
Can anyone help me on how to create this in Java? I want the name and value to be in each so that i can iterate over the collection and then get individual values.
The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:
new JSONArray()
.put(new JSONObject()
.put("name", "cases")
.put("value", 23))
.put(new JSONObject()
.put("name", "revenue")
.put("value", 34))
.put(new JSONObject()
.put("name", "1D5")
.put("value", 56))
.put(new JSONObject()
.put("name", "diag")
.put("value", 14))
.toString();
Once you have the final array, call toString on it to get the output.
What you've got there is a JSON array containing 4 JSON objects. Each object contains two keys and two values. In Java a JSON "object" is generally represented by some sort of "Map".
Try to use gson if you have to work a lot with JSON in java.
Gson is a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Here is a small example:
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]