Get Nashorn JsonObject in Java - java

In my JavaScript I have a JSON Object which I use as a parameter of a Java object. On the Java side I receive a jdk.nashorn.internal.scripts.JO4 but only the jdk.nashorn.internal.scripts.JO class exits. How can I access this JSON Object?
var test = {
"id": 10,
"Hello": "World",
"test": {
"Lorem" : "Ipsum",
"java" : true
}
}
m.call(test);

Try using ScriptObjectMirror:
public void call(ScriptObjectMirror obj) {
System.out.println(obj.get("Hello"));
}
See this article for more examples: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

With some google searches i found a solution: On the Java side, I must use a java.util.Map. So I can parse this Map to an org.json.simple.JSONObject
public void call(Map map){
JSONObject json = new JSONObject(map); // convert map to an json Object
}

Related

Null pointer observed while trying to fetch the object value from JSON array

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.

API responds with different JSON types each time

I'm getting data from a JSON API. And I'm using GSON to parse the data for my Android app. The problem is, the value for the same variable is a JSONArray in one case, but in another case, it is a JSONObject. Hence I'm unable to write the Java classes which GSON could use to parse the data.
First response - "direction" is an array
{
"route":{
"time_min":"10",
"directions":{
"direction":[
{
"direction_description":"Dummy text.",
"direction_number":"1"
},
{
"direction_description":"Dummy text.",
"direction_number":"2"
},
{
"direction_description":"Dummy text.",
"direction_number":"3"
}
]}}}
Second response - "direction" is an object
{
"route":{
"time_min":"10",
"directions":{
"direction":
{
"direction_description":"Dummy text.",
"direction_number":"1"
}
}}}
How should I write the Java classes which GSON will use for parsing?
First, Try opting JSONObject
JSONObject jOBJ = parentOBJ.optJSONObject("direction");
If the value of jOBJ is null Try getting JSONArray -
JSONOArray jARR = parentOBJ.optJSONArray("direction");
PS,
Use try.. catch() when needed.
You can use instance of.
The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface).
Object obj= jsonOBJ.get("direction");
if (obj instanceof JSONArray)
{
}
else
{
// It's JSONObject
}

Parse JSON using JSON Object

MY JSON response body from a service as follows
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
I want to parse using JSON Object in Java.
i did like this
JSONObject obj = new JSONObject(String.valueOf(responseBody));
//responbosy is a JSONObject type
obj.getString("Employee[0].name");
Please suggest how to do that
Employee is not an array, only JSONObject
So you have do something like that:
obj.getJSONObject("Employee").getString("Name");
I Think you want to have the name, yes?
Anyway, you can access it by using:
JSONObject obj = new JSONObject(String.valueOf(responseBody));
JSONObject employee = new JSONObject(obj.getJSONObject("Employee"));
employee.getString("Name");
employee.getBoolean("applied");
Reason for this is:
Everything between
{}
is an JSONObject. Everything between
[]
means it's an JSONArray.
In your String
{
"Employee": {
"Name": "Demo",
"applied": true
}
}
You've an JSONObject because of starting with {}. Within this JSONObject you have an Propertie called "Employee" which has another JSONObject nested.
Be Carefull: applied is from type boolean, since it's true/false without "". If there's a number you should get it using getInteger(). if it's a boolean you can get it using getBoolean() and elsehow you should get it using getString().
you can see all available Datatypes at http://en.wikipedia.org/wiki/JSON

Parsing JSON with java : dynamic keys

I need to create a JSON response with some dynamic fields in java. Here is an example of the JSON response I want to return :
{
"success": true,
"completed_at": 1400515821,
"<uuid>": {
type: "my_type",
...
},
"<uuid>": {
type: "my_type",
...
}
}
The "success" and the "completed_at" fields are easy to format. How can I format the fields? What would be the corresponding java object?
Basically I want to work with 2 java objects :
public class ApiResponseDTO {
private boolean success;
private DateTime completedAt;
...
}
and
public class AuthenticateResponseDTO extends ApiResponseDTO {
public List<ApplianceResponseDTO> uuids = new ArrayList<ApplianceResponseDTO>();
}
These java objects don't correspond to the expected JSON format. It would work if I could change the JSON format to have a list, but I can't change it.
Thanks a lot!
You can massage your data into JSON form using the javax.json library, specifically the JsonObjectBuilder and the JsonArrayBuilder. You'll probably want to nest a few levels of a toJson() method which will either give you the string representation you're looking for, or the JsonObject/JsonArray you desire. Something like this:
JsonArray value = null;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (ApplianceResponseDTO apr : uuids) {
builder.add(apr.toJson());
}
value = builder.build();
return value;

How to convert map of JSON objects to JSON using GSON in Java?

I have a map of JSON objects as follows:
Map<String,Object> map = HashMap<String,Object>();
map.put("first_name", "prod");
JSONObject jsonObj = new JSONObject("some complex json string here");
map.put("data", jsonObj);
Gson gson = new Gson();
String result = gson.toJson(map);
Now if the "some complex JSON string here" was:
{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }
and execute above code gives me something like:
{
"first_name": "prod",
"data": {
"map": {
"sender": {
"map": {
"id": "test test"
}
}
},
"recipients": {
"map": {
"id": "test1 test1"
}
}
}
}
}
I might have some syntax error up there, but basically I don't know why I am seeing objects wrapped around map's.
Update
according to comments, it is a bad idea to mix different json parsers.
i can understand that. but my case requires calling an external api which takes a hash map of objects that are deserialized using gson eventually.
is there any other object bedsides JSONObject that i can add to the map and still have gson create json out of it without extra 'map' structure? i do understand that i can create java beans and achieve this. but i'm looking for a simpler way since my data structure can be complex.
Update2
going one step back, i am given a xml string. and i have converted them to json object.
now i have to use an external api that takes a map which in turn gets converted to json string using gson in external service.
so i am given an xml data structure, but i need to pass a map to that function. the way i have described above produces extra 'map' structures when converted to json string using gson. i do not have control to change how the external service behaves (e.g. using gson to convert the map).
Mixing classes from two different JSON libraries will end in nothing but tears. And that's your issue; JSONObject is not part of Gson. In addition, trying to mix Java data structures with a library's parse tree representations is also a bad idea; conceptually an object in JSON is a map.
If you're going to use Gson, either use all Java objects and let Gson convert them, or use the classes from Gson:
JsonObject root = new JsonObject();
root.addProperty("first_name", "prod");
JsonElement element = new JsonParser().parse(complexJsonString);
root.addProperty("data", element);
String json = new Gson().toJson(root);
This has to do with the internal implementation of JSONObject. The class itself has an instance field of type java.util.Map with the name map.
When you parse the String
{"sender":{"id":"test test"},"recipients":{"id":"test1 test1"} }
with JSONObject, you actually have 1 root JSONObject, two nested JSONObjects, one with name sender and one with name recipients.
The hierarchy is basically like so
JSONObject.map ->
"sender" ->
JSONObject.map ->
"id" -> "test test",
"recipients" ->
JSONObject.map ->
"id" -> "test test1"
Gson serializes your objects by mapping each field value to the field name.
Listen to this man.
And this one.
I'd a similar problem and I finally resolved it using json-simple.
HashMap<String, Object> object = new HashMap<String,Object>;
// Add some values ...
// And finally convert it
String objectStr = JSONValue.toJSONString(object);
You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.
JsonObject obj = Json
.createObjectBuilder()
.add("first_name", "prod")
.add("data", Json.createObjectBuilder()
.add("sender", Json.createObjectBuilder().add("id", "test test"))
.add("recipients", Json.createObjectBuilder().add("id", "test1 test1"))).build();
Map<String, Object> prop = new HashMap<String, Object>() {
{
put(JsonGenerator.PRETTY_PRINTING, true);
}
};
JsonWriter writer = Json.createWriterFactory(prop).createWriter(System.out);
writer.writeObject(obj);
writer.close();
The output should be:
{
"first_name":"prod",
"data":{
"sender":{
"id":"test test"
},
"recipients":{
"id":"test1 test1"
}
}
}

Categories

Resources