How to find a JsonElement at any level in Json - java

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);

Related

Get data from JSON request

I'm trying to access certain data from a JSON request, but I can't get far enough in the data to get what I need.
Site that I use: https://tibiadata.com/doc-api-v2/guilds/
The good example is the 1 under "One specific guild of Tibia"
The information I'm trying to get is the name/status under guild -­> members -> characters.
This is what I do so far:
JSONObject root = new JSONObject(sb.toString()); //Get the info into root
JSONObject guildArray = root.getJSONObject("guild"); //Get the info under "guild"
JSONArray members = guildArray.getJSONArray("members"); //Get the info unders members
at this point
System.out.println(members.get(0));
would give
{"characters":[{"nick":"Coffee time","vocation":"Elite Knight","level":336,"joined":"2017-12-27","name":"Pelli Moulante","status":"online"}],"rank_title":"Leader"}
So the only part I miss, is getting into "characters" to get the name/status information.
Any idea what I'm doing wrong?
members.get(0) will return the first JsonObject in members JSONArray
{
"rank_title": "Ivory Guardian",
"characters": [
{
"name": "Tanthalas the Fourth",
"nick": "Legendary naab",
"level": 138,
"vocation": "Elder Druid",
"joined": "2008-06-17",
"status": "offline"
}, {
"name": "Bubbax",
"nick": "Deco man",
"level": 230,
"vocation": "Elder Druid",
"joined": "2014-08-29",
"status": "offline"
},
]
}
From this get the characters, JSONArray which consists of JsonObject, then iterate JSONArray using for loop
for(Object obj : members.getJsonObject(0).getJSONArray("characters")) {
JSONObject p = (JSONObject) obj;
System.out.println(p.get("name");
System.out.println(p.get("status");
}

Is there a way to name each JSONObject in an array?

{
"Object1": {
"description": "An object",
"data": "more data"
},
"Object2": {
"description": "An object",
"data": "more data"
}
}
How would I use GSON to iterate over the elements in this JSON Object to easily parse each element one by one?
Yes there is, but PrabhakarP is right, associative arrays in JSON are objects. So in your case,
{
"Object1": {
"description": "An object",
"data": "more data"
}
}
You would have a meta-object containing each array element as a property, which doesn't really make sense. You should parse it differently.
But if you still need, in GSON, then try ,
JsonArray body = gson.fromJson(yourString, JsonArray.class);
JSONObject metaObj = new JSONObject();
for (JsonElement currEle : paymentsArray) {
JSONObject currObj = currEle.getAsJsonObject();
String nameVal = currObj.get("name");
currObj.remove("name");
metaObj.addProperty(nameVal, currObj);
}
I would suggest you to add a property to each object in array and use it
I looked at the man page and found I could loop over the set of members in the object.
JsonObject obj = gson.fromJson(jsonFile, JsonObject.class);
for(Map.Entry<String, JsonElement> element : obj.entrySet()) {
Object obj = gson.fromJson(element.getValue(), Object.class);
// do stuff with the object
}

Parsing and retrieving elements in a JSON Java

JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.
Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.
You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)

A JSONObject text must begin with '{' error

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);

parse json rest response in java

I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}

Categories