I want all the URL present under the "endpoints" json.
I tried with access it through converting the String to JSON and after that using JSON parsar. But couldn't successed.
{
"process":{
"id":"epsswitch/process/create-switch-bdl",
"views":{
"selection":{
"uri":"//scp/sdf/sdf/s/df",
"controller":"scp/switching/createswitchingbdl/controllers/selection"
},
"customers":{
"uri":"//scp/vv/vv/views/Customers",
"controller":"scp/x/vc/controllers/customers"
},
"instructions":{
"uri":"//scp/df/fd/views/Information",
"controller":"scp/switching/fd/controllers/instructions"
},
"confirm":{
"uri":"//scp/switching/createswitchingbdl/views/Confirmation",
"controller":"scp/switching/createswitchingbdl/controllers/confirm"
}
},
"endpoints":{
"data":{
"uri":"/epsswitch/create/data?cc=true&al=true&ac=true"
},
"bank":{
"uri":"/fdd/df/df/v1/bank/df/",
"method":"GET"
}
}
}
There are multiple ways you can parse an JSON string. I use json simple (org.json.simple), java json are some of them. The following code uses the latter. It takes all the keys from the json string and retrieves all the values inside each key.
String sJSONString = "<your json object here>";
JSONObject jsObjects = new JSONObject(sJSONString);
//This is where you get your keys
Iterator<String> keys = jsObjects.keys();
//Use while if you need to poll for each key in JSON string
while(keys.hasNext())
{
String keyN = keys.next();
JSONObject jsoObjN = new JSONObject();
jsoObjN = (JSONObject)jsObjects.get(keyN);
//<Your logic here>
}
Following code help me to achive this.
final JsonNode studentNode = mapper.readTree(sPhone.getProcessJson());
JsonNode process = studentNode.get("process");
JsonNode endpoints = process.get("endpoints");
for (JsonNode jsonNode : endpoints) {
JsonNode uri = jsonNode.get("uri");
}
Related
I have an object something like this in my database and now my requirement is to find the value of particular field such as name and if present return true,
{
"_id" : "123",
"name" : "Team"
}
but in some case the field name itself doesn't exist. Sample can be something like this:
{
"id":1234
}
In this case I need to return false.
How can I validate if name field exist in particular object?
I was trying to use StringUtils method something like this
StringUtils.isBlank(obj.getName); But its throwing It is throwing java.lang.NullPointerException .
You can use Json schema validator. If your json will be in specific format. Please have a look at Jackson library.
JSONObject class has a method named "has". try this way,
if (json.has("name")) {
String status = json.getString("name"));
}
This will work
You can use Gson Java library to serialize and deserialize Java objects to JSON (as given below).
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(object, JsonObject.class);
Then, you can use the has method in JsonObject, to check if the key exists in it.
jsonObject.has(key)
Example:
Below is a method to check if given key exists in given json string, and get it's value.
(Instead of String, you can use your object as well. Here, I am considering the jsonStr as a String object, for better understanding.)
private String getValueFromJsonForGivenKey(String key, String jsonStr) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
if (jsonObject.has(key)) {
// The given JSON string has the given key
String value = jsonObject.get(key).getAsString();
return value;
}
return null;
}
For key id and for jsonStr { "id": "1234" }, we get 1234.
For key name and for jsonStr { "id": "1234" }, we get null.
What you can do is to use JSONObject's opt method
eg.
JSONObject jsonObject = new JSONObject(myJSONString);
String name = jsonObject.optString("name");
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'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.
I'm pretty new to world of jackson, and wanted to read the value of specific field from list of jsons (which is a response body of third-party api).
for a single json, using objectMapper works fine.
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(sampleString);
JsonNode idNode = rootNode.path("id");
System.out.println("id: "+ idNode.asText());
But I want to parse list of jsons (which is a string coming from a response body)
.So for example I receive this body:
[
{
"id":10,
"firstName":"Jack",
"primaryPhone":"9999999999",
"email":"jack#me.com"
},
{
"id":4,
"firstName":"Mark",
"primaryPhone":"9999999991",
"email":"mark#me.com"
},
{
"id":12,
"firstName":"Susaan",
"primaryPhone":"9999999992",
"email":"susan23#me.com"
}
]
I want to read the ids first, and if I find a specific id, return some other info from that block.
For example if id=4, read the firstName and email of that person.
But I'm not sure how to parsee list of json.
Any suggestions/comments is appreciated.
You can try,
JsonNode array = objectMapper.readValue(sampleString, JsonNode.class);
for(int i=0;i<array.length;i++){
JsonNode jsonNode = array.get(i);
JsonNode idNode = jsonNode.get("id");
String id = idNode.asText();
if(id.equals("4")){
JsonNode firstNameNode = jsonNode.get("firstName");
String firstName = firstNameNode.asText();
System.out.println("firstName = " + firstName);
JsonNode emailNode = jsonNode.get("email");
String email = emailNode.asText();
System.out.println("email = " + email);
break;
}
}
You can use Json Path.
So, the query would be something like this:
$[?(#.id == 4)].firstName
You can create a POJO like the one below:
class Record {
private Long id;
private String firstName;
//Getters and setters
}
And deserialise the json into List of these POJOS, e.g.:
ObjectMapper mapper = new ObjectMapper();
List<Record> records = mapper.readValue("", new TypeReference<List<Record>>() { });
Once done, you can filter out the records with stream, e.g.:
List<Record> filtered = records.stream()
.filter(r -> r.getId() = 12)
.collect(Collectors.toList());
I'm trying to get the data of this Json. As you can see the first element have a json inside of the json.
{
"client":{
"colour":"aabb11",
"height":200,
"xpos":0,
"packages":"com.samsung.incallUi",
"events":[
{
"action":"hide",
"class":"com.android.TextView",
"type":"2"
},
{
"colour":"00FF00",
"action":"show"
}
],
"width":600,
"ypos":20
},
"Map":" {red=blue, yellow=brown}",
"Country":"IT"
}
I get the json from:
Request request = new Request.Builder().url(INIT_URL).post(formBody).build();
Response response = client.newCall(request).execute();
I'm trying this, but don't work (give me an JsonSyntaxException):
...
JSONArray ja = new JSONArray(response.body().string());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String client = jo.getString("client");
String xpos = jo.getString("height");
String packages = jo.getString("xpos");
String events = jo.getString("packages");
...
}
...
The first element, "client" is an object not an array.
try
JSONObject ja= new JSONObject(response.body().string());
I recommend you to take a look into a JSON parser, such us Jackson or Gson.
Will do your life much easier.
//Jackson example
Client client = new ObjectMapper().readValue(jsonString, Client.class);
Just define your Client class with the fields in the JSON
I strongly recommend using Gson. If you can't get it right with gson, that means, your model is not correct. If you have a hard time creating the model for the json, you can auto generate the model instead of creating it your self.