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
Related
I have an api which returns data in the below format when i use the clientbuilder get():
final Response response = ClientBuilder.newClient().target("url").queryParam("CustomerQuery", jsonarr).request(MediaType.APPLICATION_JSON).get();
String actual = response.readEntity(String.class);
System.out.println(actual);
Result:
{"_id":{"timestamp":1649320244,"date":"2022-04-07T08:30:44.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:44.011+00:00"}],"MyDetails":{"Query":"query1^^","name":"NEH","address":"XXX","Format":"xml","Version":"2"}}
{"_id":{"timestamp":1649320255,"date":"2022-04-07T08:30:55.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:55.011+00:00"}],"MyDetails":{"Query":"query2^^^","name":"ABC","address":"YYY","Format":"xml","Version":"1"}}
I need to extract fields under MyDetails in the above string and i tried using :
final Response response = ClientBuilder.newClient().target("url").request(MediaType.APPLICATION_JSON).get();
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
System.out.println(jsonReader.readObject());
Please let me know how can i extract the fields.
If you have questions about how to use a JsonObject, read the Javadoc https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonObject o = jsonReader.readObject();
JsonObject details = o.getJsonObject("MyDetails");
// details.get...
Alternatively, use a different http client like Retrofit that encourages direct object mapping
There are many ways to do what you want to do. I will just describe some of them. You can use several Json parsing libraries. The most popular ones are Json-Jackson also known as faster XML (See link here). You can use method readValue of ObjectMapper class. For class parameter you can use Map.class or your custom written class that will reflect the structure of your Json.
Than there is Gson library, with its user guide
But also if you want a simplistic solution, I wrote my own open-source library that includes JsonUtils class that is a thin wrapper over Json-Jackson library that gives you a very simple solution. In your case it may look like this (assuming variable json is a String that contains your Json string):
try {
Map<String, Object>map = JsonUtils.readObjectFromJsonString(json, Map.class);
Map details = map.get("MyDetails");
} catch(IOException ioe) {
...
}
Map details will contain a map with all your keys and values from section "MyDetails". If you want to use this library here is where to get it: Its called MgntUtils and you can get it on Github with Javadoc and source code. It is available as maven artifacts as well. Here is a Javadoc for JsonUtils class
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
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.
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.
I have the following JSON array in my JSON.java file:
ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");
I would like to send array to the AJAX script located in AJAX.jsp.
I know how to receive the text in AJAX via e.g.
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
But I don't know how to send the array from the server to the client!
Appreciate your help
ok First:
ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");
JSONArray array = new JSONArray();
This can't compile... you have a duplicate variable array ;-)
Second: create a servlet/Struts Action/etc that will contains the code that will create your array. Then transform it in JSON with a JSON library. Finally, put the string in the response of your servlet/Struts Action/etc.
Use JQuery to ease your effort on the Ajax call. It will help you with the Ajax call and the transformation back to Json from the string received in the http response.
Ex:
your ajax call should be like that (with JQuery)
$.getJSON("http://yourserver/JSONServlet",
function(data){
alert (data) // this will show your actual json array
});
});
and your servlet should look like that:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.JSONArray;
public class JSONServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
JSONArray arrayObj=new JSONArray();
arrayObj.add("D");
arrayObj.add("A");
arrayObj.add("L");
arrayObj.add("D");
arrayObj.add("A");
arrayObj.add("TEST");
PrintWriter out = response.getWriter();
out.println(arrayObj);
for(int i=0;i<arrayObj.size();i++){
out.println(arrayObj.getString(i));
}
}
}
you basically use certain classes in java like the ones defined here: http://json.org/java/ convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set..
here is code for the same:
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
for more http://code.google.com/p/json-simple/wiki/EncodingExamples
Instead of using org.json's barebones library as suggested already, consider using data-binding JSON library like Jackson or GSON (there are many others as well), in which case you can simplify servlet case (with Jackson) to:
new ObjectMapper().writeValue(response.getOutputStream(), array);
and that's all you need.
And for even simpler handling, JAX-RS services (Jersey, RESTeasy, CXF) can further simplify handling, to reduce code you need compared to raw servlets. JAX-RS + JSON is the modern way to implement web services on Java, so might make sense to learn it now.
The simplest way is construct a json string in java file and return that json string to client.
Javascript provides a eval() method which inverts json string to json object.
Then you can perform what ever operations you need.