Jackson serialize multiple objects into one - java

I've got an Ajax call to populate multiple fields in the front end from Hibernate Objects. That's why I would like to return multiple Java Hibernate to Json serialized objects to Ajax from Spring. Currently I do:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson()
{
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try
{
json = ow.writeValueAsString(result);
} catch (JsonGenerationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
This works fine and returns a json object to ajax but I have multiple objects like that so what I want is to nest all these objects in one json object and return the latter to my ajax so I can populate all fields using one object rather than making multiple ajax calls for each object I need. So for example I would to have something like:
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(result);
List<SecondObject> secondObject = serviceSecondObject.getSecondObject(pk);
String json2 = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json2 = ow.writeValueAsString(secondObject );
NewJsonObject.add(json)
NewJsonObject.add(json2)
return newJsonObject;

You should be able to just use a Map (since JSON Objects aren't anything different than a Map) to hold your objects:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson() {
Map<String, Object> theMap = new LinkedHashMap<>();
// if you don't care about order just use a regular HashMap
// put your objects in the Map with their names as keys
theMap.put("someObject", someModelObject);
// write the map using your code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
return ow.writeValueAsString(theMap);
}
You can now access all the objects in the Map in your JS, since the Map will get serialized as a JSON-Object:
response.someObject == { // JSON Serialization of someModelObject }

Related

Getting value from json item in java

I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}

Java Nashorn build json array object in java can't find way

I try to create java json array ,
can't find any way to create them using Nashorn
i can create simple objects ...
private void createJsonObject() {
try {
final Map<String, Object> newMap = new HashMap<>();
newMap.put("foo",1);
newMap.put("bar", true);
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.putAll(newMap);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result : {"bar":true,"foo":1}
Here i try to create array but im getting empty json
private void createJsonObject() {
try {
List<String> returnList = new ArrayList<>();
returnList.add("x");
returnList.add("y");
ScriptObjectMirror json = (ScriptObjectMirror) this.engine.eval("JSON");
json.put("test",returnList);
this.engine.put("jsonObject", json);
String result = (String) this.engine.eval("JSON.stringify(jsonObject)");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
}
Result: {}
The end goal is to build array of objects in memory using java native tools without using dependencies

How to parsing JSON like this?

I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}

Converting Json to Hashmap [duplicate]

This question already has answers here:
How to convert a JSON string to a Map<String, String> with Jackson JSON
(11 answers)
Closed 6 years ago.
I have a json string
{
{
key1:[values1]
},
{
key2:[values2]
}
}
I want to convert it into HashMap(String,Object) in java.
I have been using normal json parsing, where I create a jsonObject from the json string and extract jsonArrays from the jsonObject. Is there any direct API to convert it?
Always use jackson for JSON manipulation.
Check this out for other useful examples:
https://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
Regarding your question:
public class JsonMapExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":29}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
System.out.println(map);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

can I set json to be pretty print only in some attributes?

I have a json with many attributes.
I want some of them to be inline. Meaning with no new break lines.
Here is my code today:
private String serializeToJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}
how can I set it to be not "pretty print" for attribute path like this { "path" : { "segmentId" : 31788674, "nodeId" : 26161441, "x" : -74.236605 ...
I serialized this specific property to inline json string separately.
public ResultUiShort(ResultLong result) {
this.path = stringUtils.toInlineJson(result.path);
...
}
and
public <T> String toInlineJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}

Categories