Parsing Complex Json with Gson Java - Only nodes - java

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() {}

Related

Json inside json not working in spring boot

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.

Out of START_ARRAY token while reading a JSON in servlet

I have to create Java object from JSON string received in servlet
Below is the JSON
[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade#gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]
I tried to change the JSON that is by replacing [ by { and ] by } but it gives some other error.
My jackson code where I am getting exception is
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);
And the Enroll class is simple bean class with setter and getter
public class Enrole {
private String name;
private String email;
private long contactno;
private String address;
This is one of the way
try {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"name\",\"value\":\"Shital\"},{\"name\":\"email\",\"value\":\"swankhade#gmail.com\"},{\"name\":\"contactno\",\"value\":\"9920042776\"},{\"name\":\"Address\",\"value\":\"a6 102 Elementa\"}]";
KeyValue[] jsonObjArr = mapper.readValue(json, KeyValue[].class);
Enrole enrol = new Enrole();
for (int i = 0; i < jsonObjArr.length; i++) {
KeyValue keyVal = jsonObjArr[i];
if ("name".equals(keyVal.getName())) {
enrol.setName(keyVal.getValue());
}
if ("email".equals(keyVal.getName())) {
enrol.setEmail(keyVal.getValue());
}
if ("contactno".equals(keyVal.getName())) {
enrol.setContactno(Long.parseLong(keyVal.getValue()));
}
if ("address".equals(keyVal.getName())) {
enrol.setAddress(keyVal.getValue());
}
}
System.out.println(enrol.getName());
System.out.println(enrol.getContactno());
System.out.println(enrol.getAddress());
System.out.println(enrol.getEmail());
} catch (Exception e) {
System.out.println("Exception " + e);
}
Class with Key and Value :
class KeyValue {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Model Class
class Enrole {
private String name;
private String email;
private long contactno;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getContactno() {
return contactno;
}
public void setContactno(long contactno) {
this.contactno = contactno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

How to use Jackson ObjectMapper to convert to Pojo for multiple data

I would like to convert the following string/ JSONObject to POJO,
{"list":["\r\n{\r\n\"id\":\"1\",\r\n\"protocol\":\"udp\",\r\n\"srcPorts= \":\"3000-4000 \",\r\n\"destPorts\":\"1790-2000\"\r\n}","\r\n{\r\n\"id\":\"2\",\r\n \"protocol\":\"tcp\",\r\n\"srcPorts\":\"3000-4000\",\r\n\"destPorts\":\"1790-2000 \"\r\n}"],"user":"\r\n{\r\n\"name\":\"John\",\r\n\"address\":\"x.x.x.x\",\r\n\"email \":\"john#p.com\"\r\n}"}
How do I convert to Pojo using Jackson ObjectMapper.
The 2 Pojo classes are as follows.
The user part in the string above should map to the java file - User.java
public class User
{
private String name;
private String address;
private String email;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setaddress(String Address)
{
this.address = address;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
}
The List part in the string above should map to the java file - TestCase.java
public class TestCase
{
private String id;
private String protocol;
private String srcPorts;
private String destPorts;
public String getProtocol()
{
return protocol;
}
public void setProtocol(String protocol)
{
this.protocol = protocol;
}
public String getSrcPorts()
{
return srcPorts;
}
public void setSrcPorts(String srcPorts)
{
this.srcPorts = srcPorts;
}
public String getDestPorts()
{
return destPorts;
}
public void setDestPorts(String destPorts)
{
this.destPorts = destPorts;
}
public String getID()
{
return id;
}
public void setID(String id)
{
this.id = id;
}
}
Following code should help.
class ParseJson{
private User user;
private TestCase testCase;
//getter and setter methods
}
//and then call objectMapper -
String jsonString = "";//Json input
ObjectMapper mapper = new ObjectMapper();
ParseJson parsedJson = mapper.readValue(jsonString, ParseJson.class);
User user = parsedJson.getUser();
TestCase testCase = parsedJson.getTestCase();
Since your JSON object does not contain any type information, the best approach would be to use a custom deserializer class for Jackson, at least for the outer class. Alternatively, you can try annotating your POJO classes with Jackson annotations, and hope that the Right Thing happens.
In any case, you will have to make Jackson aware of your context by calling one of the ObjectMapper.readValue() methods with the proper class type argument, so that Jackson will know what it is that is being deserialized.

How should I define my model class for an arrangement with Gson?

I have the following JSON:
{
_id: "5252fdf424f1e7fbf7000004",
address: "Calle 1000",
city: "ConcepciĆ³n",
created_at: "2013-10-07T18:31:19.375Z",
description: "",
name: "Joctos",
phone: "94967994",
updated_at: "2013-12-09T13:03:07.328Z",
happy_hour: {
active: false,
type: 1,
all_day: false,
start: "2013-12-17T03:30:00.000Z",
end: "2013-12-17T05:00:00.000Z"
}
}
Tell them to receive and work with JSON GSON me to believe an object, the probleam is that defined the object follows
public class StoreModel {
#SerializedName("_id")
private String _id;
#SerializedName("address")
private String address;
#SerializedName("city")
private String city;
#SerializedName("created_at")
private String created_at;
#SerializedName("description")
private String description;
#SerializedName("name")
private String name;
#SerializedName("phone")
private String phone;
#SerializedName("updated_at")
private String updated_at;
public String get_id() {
return this._id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCreated_at() {
return this.created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUpdated_at() {
return this.updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
How should I define my model to get the "happy_hours" data?
StoreModel class will contain the object of happy_hours
Create a HappyHours class with appropriate attributes and add an attribute happyHours to your StoreModel :
#SerializedName("happy_hours")
private HappyHours happyHours;
For Date objects try "Date start;" and "Date end;"
If it doesn't work, you have to write an adapter :
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateGsonDeserializer());
gsonBuilder.create();
public class DateGsonDeserializer implements JsonDeserializer<Date> {
#Override
public Date deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
// just write the right formatter from SimpleDateFormat
return formatToDate(jsonElement.getAsString())
}
}

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