I have a JSON string where i want to get the value of one field which is nested in multiple objects. How can I get that field in a nice and performant way? Here's the code I tried so far. It's working, but it's quite lengthy code. I'm looking for a better solution.
Json Response
{
"status":"success",
"response":{
"setId":1,
"response":{
"match":{
"matches":{
"matchesSchema":{
"rules":[
{
"ruleId":"Abs"
}
]
}
}
}
}
}
lengthy code:
JsonParser jp=new JsonParser();
Object obj = jp.parse(JSONString);
JSONObject jsonObject =(JSONObject) (obj);
JSONObject get1 = jsonObject.getJSONObject("response");
JSONObject get2 = get1 .getJSONObject("response");
JSONObject get3 = get2 .getJSONObject("match");
JSONObject get4 = get3 .getJSONObject("matches");
JSONObject get5 = get4 .getJSONObject("matchesSchema");
JSONObject get6 = get5 .getJSONObject("rules");
JSONArray result = get6 .getJSONArray("rules");
JSONObject result1 = result.getJSONObject(0);
String lat = result1 .getString("rule");
The result is
ruleId = Abs
is there a good alternative for fetching the ruleId from the nested json object (something like response.response.match.matches.matchesSchema.rules.ruleId)
You can use Jackson's JsonNode with JsonPath to get ruleId as follows:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj = mapper.readTree(JSONString);
String lat = jsonObj.at("/response/response/match/matches/matchesSchema/rules/0/ruleId").asText()
It's also null-safe and returns a MissingNode object on a null node that returns an empty string when you do a .asText()
It's super easy with JsonPath.
String ruleId = JsonPath.read(jsonString, "$.response.response.match.matches.matchesSchema.rules[0].ruleId");
Or if you read the path multiple times, it's better to pre-compile JsonPath expression
JsonPath ruleIdPath = JsonPath.compile("$.response.response.match.matches.matchesSchema.rules[0].ruleId");
String ruleId = ruleIdPath.read(json);
Related
I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);
i have a json-object named jsonObject
{
"action":"Read",
"infos":[
{
"value":0.0350661,
"key":"first"
}
]
}
i wanna to print the json-object to with the following form
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
if i use jsonObject.toString() method i will get
{"action":"Read","infos":"[{\"value\":0.0350661,\"key\":\"first\"}]"}
if i use StringEscapeUtils.unescapeJava(jsonObject.toString()) method i will get
{"action":"Read","infos":"[{"value":0.0350661,"key":"first"}]"}
if i use jackson mapper with the following code
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
String jsonString = mapper.writeValueAsString(getDebugInfo())
i will get jsonString as
{"nameValuePairs":{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}}
is there any solution to get the desired output json-string?
JSON Structure
You have that as an object, that is why quotes are not present there.
In your example, an array object is present, at the Json structure.
Code/Java
While printing at Console, the json body's every Key & Value toString() are referred .
That is why the Double Quotes present, as Strings are getting used!
Here I have tried the below code using GSON library, and it is printing me the correct json as shown above.
public static void main ( String [] args ) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "Read");
JsonArray jsonArr = new JsonArray();
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("value", 0.0350661);
jsonObject2.addProperty("key", "first");
jsonArr.add(jsonObject2);
jsonObject.add("infos", jsonArr);
String jsonString = jsonObject.toString();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement json = gson.fromJson(jsonString,JsonElement.class);
String jsonInString = gson.toJson(json);
System.out.println(jsonInString);
}
OUTPUT:
{
"action": "Read",
"infos": [
{
"value": 0.0350661,
"key": "first"
}
]
}
Even if I am forming the jsonObject using org.json, and simple printing it using System.out.println(jsonObject.toString()); on console, m getting the result like this.
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
So here, not sure how you have formed your jsonObject.
I have a JSON object as follows:
{
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"user":{
"pk":17,
"username":"user1",
"email":"user1#gmail.com",
"first_name":"",
"last_name":""
}
}
I am trying to get two JSON object from it; token and user. I have tried two different ways but both are failing:
//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());
jsonObjectRoot = new JSONObject(response.body().string());
Could any one please let me know how I could split this to two JSON objects?
You can split it this way:
// source object
JSONObject sourceObject = new JSONObject(sourceJson);
String tokenKey = "token";
// create new object for token
JSONObject tokenObject = new JSONObject();
// transplant token to new object
tokenObject.append(tokenKey, sourceObject.remove(tokenKey));
// if append method does not exist use put
// tokenObject.put(tokenKey, sourceObject.remove(tokenKey));
System.out.println("Token object => " + tokenObject);
System.out.println("User object => " + sourceObject);
Above code prints:
Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}
User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}}
You can parse a json string with
var obj = JSON.parse(jsonString);
You can filter sub parts of a json object by simply addressing them
var token = obj.token;
var user = obj.user;
The safer / cleaner way to do it is to create a POJO and deserialize your JSON into it using Jackson. Your pojo:
public class MyObject {
String token;
User user;
static class User {
int pk;
String username;
String email;
String first_name;
String last_name;
}
}
Then, when you want to deserialize:
import com.fasterxml.jackson.databind.ObjectMapper;
and
ObjectMapper mapper = new ObjectMapper();
MyObject myObject = mapper.readValue(jsonString, MyObject.class);
String token = myObject.token;
User user = myObject.user;
...
I recently faced the same situation, I used the below code which worked for me:
JSONObject jo1 = new JSONObject(output);
JSONObject tokenObject = new JSONObject();
tokenObject.put("token", jo1.get("token"));
JSONObject userObject = new JSONObject();
userObject.put("user", jo1.get("user"));
Here I am creating a new empty JSONObject and then put the retrieved object from the original object in the newly created JSONObject.
You can also verify the output by just sysout:
System.out.println("token:" + tokenObject.get("token"));
System.out.println("user:" + userObject.get("user"));
Output in my case :
token::eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
user:{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}
Yep. It is a JSON string.
Using like this
JSONParser jparse=new JSONParser();
JSONObject jObj=(JSONObject)jParse.parse(jsonString);
jObj will contain json Object now.
I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.
So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}