Json inside json not working in spring boot - java

I am trying to use JSON inside a JSON request.
for example:
{
"name":"newdeeeepaajlf",
"category":"fsafaa",
"jsonData":{
"a":"value"
}
}
now when I am trying to get it in my DTO which has
private JSONObject jsonData;
it gets converted in a blank JSON
{}
I am stuck in this.

We can use map to convert the data
public class TestModel {
private String name;
private String category;
private Map<String, Object> jsonObj;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Map<String, Object> getJsonObj() {
return jsonObj;
}
public void setJsonObj(Map<String, Object> jsonObj) {
this.jsonObj = jsonObj;
}
}
and use above class from controller like below
#PostMapping("/test")
public boolean test(#RequestBody TestModel model) {
System.out.println(model.getCategory());
System.out.println(model.getName());
JSONObject jsonObj = new JSONObject(model.getJsonObj());
System.out.println(jsonObj);
return true;
}
For request
{
"category":"json",
"name":"name",
"jsonObj": {
"a": "value"
}
}
it will print
json
name
{a=value}

you have a error in json if you have json something like below.
{
"name": "newdeeeepaajlf",
"category": "fsafaa",
"jsonData": {
"a": "value"
}
}
you can use this as a class
public class Codebeautify {
private String name;
private String category;
JsonData jsonDataObject;
// Getter Methods
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public JsonData getJsonData() {
return jsonDataObject;
}
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setCategory(String category) {
this.category = category;
}
public void setJsonData(JsonData jsonDataObject) {
this.jsonDataObject = jsonDataObject;
}
}
public class JsonData {
private String a;
// Getter Methods
public String getA() {
return a;
}
// Setter Methods
public void setA(String a) {
this.a = a;
}
}
also json within json is working with in spring boot its a very common scenario. use ObjectMapper to map json with class.

Related

How to Get Json object and Json Array in Same KEY by retrofit for android

I am getting JSON Object when their is only one response(items) or JSON Array response but i want to array and object response.How to handle JSON Response?
JSON ARRAY when their is more than one items.And JSON OBJECT when their is only one items
.
{
"product":[
{
"items":[
{
"name":"foo",
"title":"toy"
},
{
"name":"foo",
"title":"toy"
}
]
},
{ "items":
{
"name":"foo",
"title":"toy"
}
}
]
}
First create model for this json Response using json to p
public class Example {
#SerializedName("product")
#Expose
private List<Product> product = null;
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
public class Item {
#SerializedName("name")
#Expose
private String name;
#SerializedName("title")
#Expose
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Product {
#SerializedName("items")
#Expose
private List<Item> items = null;
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Pass this Exmaple class into your response like
Call and get the data usning model

Custom JSON response with Spring MVC

Model
public class Organisation {
private String name;
public Organisation() { }
public Organisation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
controller
#RequestMapping(method = RequestMethod.GET)
public List<Organisation> getAll() {
Organisation organisation = new Organisation("google");
List<Organisation> organisations = new ArrayList<>();
organisations.add(organisation);
return organisations;
}
This will give out response like this:
[
{
"name": "google"
}
]
What if we want something like this:
{
"data": [{
"type": "organisations"
"attributes": {
"name": "google"
}
]
}
So how to customize the json. I know that Spring MVC by default uses Jackson to convert models into JSON. Is there a way to customize it. I am trying to send response in JSONApi standard. Also can someone tell how to create links in responses
Create Classes as:
public class Object1 {
private List<Object2> data;
public Object1() {
}
public Object1(List<Object2> data) {
this.data = data;
}
//getters and setters
}
public class Object2 {
private String type;
private Object3 attributes;
public Object2() {
}
public Object2(String type, Object3 attributes) {
this.type = type;
this.attributes = attributes;
}
//getters and setters
}
public class Object3 {
private String name;
public Object3(String name) {
this.name = name;
}
public Object3() {
}
//getters and setters
}
Now your controller method shoul be like:
#RequestMapping(method = RequestMethod.GET)
public Object3 getAll() {
List<Object2> data = new ArrayList<>();
data.add(new Object2("organisations", new Object3("google")));
return new Object1(data);
}

want to deserialize json string into java object with arraylist

java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));

Parsing Complex Json with Gson Java - Only nodes

I have this Json structure and I need to get the information for "myId", "name", "adress1" and "city".
{
"InformationResponse":{
"Id":"122212",
"customerSessionId":"007",
"Summary":{
"myId":1234567,
"name":"Casino",
"address1":"13 Street",
"city":"Las Vegas",
},
...
I am using Gson (Java).
I created 3 Class (InformationResponse, Summary and Main)
public class Summary {
private String myId;
private String name;
private String city;
public String getMyId() {
return myId;
}
public void setMyId(String myId) {
this.myId= myId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString(){
return getMyId() + ", "+getName()+", "+getCity();
}
}
MyObject.class
public class MyObject{
private Summary summary;
public Summary getSummary() {
return address;
}
#Override
public String toString(){
sb.append("Summary="+getSummary()+"\n");
return sb.toString();
}
}
In the Main I can see my Json file and I am doing this:
// Get Gson object
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// parse json string to object
MyObject myobject1 = gson.fromJson(json, MyObject.class);
But I have null everytime.
Thanks for your help!
Jean M.
Try This #SerializedName("Id")
private String myId;
Gson requires a default no args constructor:
https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
Try adding a public no-args constructor to both your Summary and MyObject classes.
public Summary() {}
public MyObject() {}

Converting json format using java bean

I have a json string something similar
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","geo_position":{"latitude":52.39886,"longitude":13.06566}},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","geo_position":{"latitude":44.66978,"longitude":-74.98131}}]}
I am trying to convert to
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","latitude":52.39886,"longitude":13.06566},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","latitude":44.66978,"longitude":-74.98131}]}
I am converting to java and again converting back using But I am gettin null in data
SourceJSON data=new Gson().fromJson(jsonArray, SourceJSON.class);
DestinationJSON destdata = new DestinationJSON();
destdata.setLatitide(data.getGeoLocation().getLatitide());
destdata.setLongitude(data.getGeoLocation().getLongitude());
destdata.setId(data.getId());
destdata.setType(data.getType());
destdata.setName(data.getName());
destdata.set_type(data.get_type());
Gson gson = new Gson();
String json = gson.toJson(destdata);
below are my beans
public class SourceJSON implements Serializable {
private List<GEOLocation> geoLocations;
private String _type;
private String id;
private String name;
private String type;
public String get_type() {
return _type;
}
public List<GEOLocation> getGeoLocations() {
return geoLocations;
}
public void setGeoLocations(List<GEOLocation> geoLocations) {
this.geoLocations = geoLocations;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
and
public class GEOLocation implements Serializable{
private String latitide;
private String longitude;
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
and destination java
public class DestinationJSON implements Serializable {
private String _type;
private String id;
private String name;
private String type;
private String latitide;
private String longitude;
public String get_type() {
return _type;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
All you need is this. You can try this class in your IDE with a simple copy&paste.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20433539{
public static void main(String[] args){
String json = "{\"results\":"+
"[{\"_type\":\"Position\",\"_id\":377078,\"name\":\"Potsdam, Germany\",\"type\":\"location\",\"geo_position\":{\"latitude\":52.39886,\"longitude\":13.06566}},"+
"{\"_type\":\"Position\",\"_id\":410978,\"name\":\"Potsdam, USA\",\"type\":\"location\",\"geo_position\":{\"latitude\":44.66978,\"longitude\":-74.98131}}]}";
Gson gson = new Gson();
Map m = gson.fromJson(json, Map.class);
List<Map> innerList = (List<Map>) m.get("results");
for(Map result: innerList){
Map<String, Double> geo_position = (Map<String, Double>) result.get("geo_position");
result.put("latitude", geo_position.get("latitude"));
result.put("longitude", geo_position.get("longitude"));
result.remove("geo_position");
}
System.out.println(gson.toJson(m));
}
}
Of course, it works under the assumption that you always want to flat geo information.
Explanation: It's convenient to use POJO when working with Gson, but it's not the only way. Gson can also deseralize to Arrays/Maps if you do not specify the expected result. So I did, and then I manipulated the structure to unfold your data. After that, Gson can serialize Arrays/Maps structure again to your desidered JSON.

Categories