How to convert Java Pojo to Nashorn Json? - java

I have a Java object that I want to turn into a json object and pass to the Nashorn javascript engine. It is surprisingly difficult to google an answer for this! Can someone tell me how to do it?
I tried this:
ObjectMapper mapper = new ObjectMapper();
String inputModelAsString = mapper.writeValueAsString(inputModel);
And then passing the string json to the function:
result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, inputModelAsString);
But it was passed as a string, not as a json.

You can convert json from engine by
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("("+inputModelAsString+")");
Then you can pass the json object in you code
result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, json);

I faced a similar issue and handled it in a slightly different way.
I wouldn't access the class ScriptObjectMirror directly as it's part of the internal Nashorn's API and therefore prone to change.
You may try something like this:
engine.eval("var inputModel = " + inputModel + ";");
Object json = engine.get("inputModel");

you could use inbuild JSON feature in Nashorn as mentioned in
Nashorn JSON stringify

Related

How to access nested elements from a JSON using Java (Bing-Search-API)

I have this JSON that I retrieved using Bing-Search-API. Now, I'm not sure how to access the nested elements using GSON. I already made the source files for the JSON Structure Data.
If I do this:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
It is going to throw me that is not a JsonArray, so If I change it to JsonObject, how can I retrieve the String MediaUrl from Results.java?
Thank you
Based on the javadoc of Gson class:
Gson gson = new Gson();
Response response = gson.fromJson(jsonText, Response.class);
Results firstResult = response.getD().getResults().get(0);
System.out.println(firstResult.getMediaUrl());
So you don't need to use the JsonParser directly.
Your java classes have to be modified a little bit for this to work:
the type of results field in D.java has to be List<Results> so that Gson can find out the class of objects to populate with.
the naming of attributes/fields is inconsistent, some starts with lower case, others with uppercase. Make sure they are the same in the java classes and in the json string (considering case sensitivity). This issue might be addressed with using the appropriate FieldNamingStrategy for serialization/deserialization.

Java - JSONObject charset

I'm using JSONObject from org.json.*
I need to construct JSONObject with string fields like this
field:"englishletters123\u1234\u3456"//UTF-8 encoding
so, I'm doing this
myJSONObject.put("field", myString);
But instead of this I'm getting object with fluent (non-english) letters instead of their UTF-8 representation.
String newString = new String(oldString.getBytes(...), ...);
myJSONObject.put("field", newString);
doesn't work as well
Is there any way to make such operation? Maybe I should use some other library?
I'm not overly familiar with that JSON serialization library, but since you asked, the GSON library from google is amazing. It handles nearly everything through reflection, it's as simple as creating an object that fit the description of the JSON text you are attempting to create.
for example:
public class Thing{
public String field = "whatever you want";
}
Gson gson = new Gson();
String jsonString = gson.toJson(new Thing());
de-serializing is simple too:
Thing t = gson.fromJson(jsonString, Thing.class);
Of course, there's much more to the library, but that's the basics of it.

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

How to decode a json string with gson in java?

I have a json string (the stream of social network Qaiku). How can I decode it in Java?
I've searched but any results work for me.
Thank you.
Standard way of object de-serialization is the following:
Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);
For primitives corresponding class should be used instead of MyType.
You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.
As an example using Gson, you could do the following
Gson gson = new Gson();
gson.fromJson(value, type);
where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.
The following example shows decoding a JSON string into a list of domain objects called Table:
http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/
In order to do that the type needs to be specified as:
Type type = new TypeToken<List<Table>>(){}.getType();
Gson is available here:
http://code.google.com/p/google-gson/

What is the JSP equivalent to json_encode ( in PHP )?

I am trying to encode a JSP servlet into JSON. What's the equivalent in JSP to json_encode() in PHP ?
JSP/Servlet isn't that high-level as PHP which has practically "anything built-in". In Java you've more freedom to choose from libraries. There are several JSON libraries in Java available which you can implement in your webapp, the popular ones being under each JSON.org, Jackson and Google Gson.
We use here Gson to our satisfaction. It has excellent support for parameterized collections and (nested) Javabeans. It's basically as simple as follows:
String json = new Gson().toJson(anyObject); // anyObject = List<Bean>, Map<K, Bean>, Bean, String, etc..
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Converting JSON to a fullworthy Javabean is also simple with Gson, see this example.
Gson is pretty cool.
Its almost the same as json_encode. Note that an encoded empty string in json_encodeevaluates to "\"\""
In Gson it returns ""
There is a list of several Java libraries that handle JSON encoding at the bottom of http://json.org/ — take your pick.
json_encode in php is similar to following package in java
dependency:
import com.fasterxml.jackson.databind.ObjectMapper;
code :
Map<Object,Object> dataArray = {some data in map}
ObjectMapper objMapper = new ObjectMapper();
String jsonString = objMapper.writeValueAsString(dataArray);
jsonString is if the final result like son_encode in php, which you can achieve with objectMapper class

Categories

Resources