Convert Java complex object to Json - java

I need to convert the following Class:
package comS309.traxz.data;
import java.util.Collection;
import org.json.JSONException;
import org.json.JSONObject;
public class ExerciseSession {
public String DateCreated;
public String TotalTime;
public String CaloriesBurned;
public String AvgSpeed;
public String SessionName;
public String Distance;
public String SessionType;
public String UserId;
public Collection<LatLon> LatLons;
}
Where LatLon is as follows:
public class LatLon {
public String LatLonId;
public String Latitude;
public String Longitude;
public String ExerciseSessionId;
public String LLAveSpeed;
public String Distance;
}
So the Class ExerciseSession has a collection of LatLon objects. Now I need to convert The ExerciseSession Class into a Json format from java and send it to my server.
I am doing this on the android OS, if that matters.
My current solution is this:
JSONObject ExerciseSessionJSOBJ = new JSONObject();
ExerciseSessionJSOBJ.put("DateCreated", this.DateCreated);
ExerciseSessionJSOBJ.put("TotalTime", this.TotalTime);
ExerciseSessionJSOBJ.put("CaloriesBurned", this.CaloriesBurned);
ExerciseSessionJSOBJ.put("AvgSpeed", this.AvgSpeed);
ExerciseSessionJSOBJ.put("SessionName", this.SessionName);
ExerciseSessionJSOBJ.put("Distance", this.Distance);
ExerciseSessionJSOBJ.put("SessionType", this.SessionType);
ExerciseSessionJSOBJ.put("UserId", this.UserId);
//add the collection
for(LatLon l: LatLons)
{
ExerciseSessionJSOBJ.accumulate("LatLons", l);
}
I am not sure this is valid.. I am a novice with Json and need help.
Thanks in advance for the help!

This is very easy to do using Google's GSON library. Here's an example use:
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(myComplexObject);
And to get the object back:
Gson gson = new Gson();
MyComplexObject myComplexObject = gson.fromJson(jsonRepresentation, MyComplexObject.class);
http://code.google.com/p/google-gson/

You can also serialize the object using flexjson: http://flexjson.sourceforge.net/

I think using the accumulate is correct. See: http://www.json.org/javadoc/org/json/JSONObject.html#accumulate(java.lang.String,%20java.lang.Object)
But you need to create a JSONObject for each LatLon as you do for the ExerciseSession object.
Then, the following line is wrong:
ExerciseSessionJSOBJ.accumulate("LatLons", l);
"l" must be transformed.

I would really suggest you avoid using JSONObject to convert between Strings and Java objects. It will probably claim your sanity if you have to do too much of it. As an alternative, I'm a big fan of Jackson, which does what you describe in a really pleasant and simple way.
As a basic example,
public static class LatLon {
public final String LatLonId;
public final String Latitude;
public final String Longitude;
public final String ExerciseSessionId;
public final String LLAveSpeed;
public final String Distance;
#JsonCreator
public LatLon(#JsonProperty("distance") String distance,
#JsonProperty("exerciseSessionId") String exerciseSessionId,
#JsonProperty("latitude") String latitude,
#JsonProperty("latLonId") String latLonId,
#JsonProperty("LLAveSpeed") String LLAveSpeed,
#JsonProperty("longitude") String longitude) {
this.Distance = distance;
this.ExerciseSessionId = exerciseSessionId;
this.Latitude = latitude;
this.LatLonId = latLonId;
this.LLAveSpeed = LLAveSpeed;
this.Longitude = longitude;
}
public static void something() {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"LLAveSpeed\":\"123\",\"Distance\":\"123\","
+ "\"ExerciseSessionId\":\"123\",\"LatLonId\":\"123\","
+ "\"Latitude\":\"123\",\"Longitude\":\"123\"}";
try {
//turn the json string into a LatLon object.
LatLon latLon = mapper.readValue(json, LatLon.class);
//turn the latLon object into a new JSON string
String newJson = mapper.writeValueAsString(latLon);
//confirm that the strings are equal
Log.w("JacksonDemo", "Are they equal? " + json.equals(newJson));
}
catch (IOException e) {
e.printStackTrace();
}
}
}
This outputs Are they equal? true.
So you use readValue() to convert json to a Java object, writeValueAsString() to write an object back into json. #JsonCreator marks the constructor Jackson should use to convert betwee json and Java. #JsonProperty("jsonKeyName") marks the name of a variable in the json string and the Java variable it should map to.
This is a little confusing at first but saves a lot of time once you figure it out. Let me know if anything is unclear.

Related

Need to manipulate returned JSON Object and extract a portion to a List

I'm consuming an external API, for which a JSON Object is returned. Contained in that Object response is an array that I need to extract and set to a List of a particular entity type. Java, however, is not a language that I'm very familiar with, so I'm having problems attempting to figure this out.
I've created a type of wrapper class to work with this in the setter.
The best I've come up with that compiles is below, but produces an error that I can't figure out.
public void setFlights(Object responseBody) {
String responseString = responseBody.toString();
JSONObject responseJSONObject = new JSONObject(responseString);
JSONArray responseJSONArray = responseJSONObject.getJSONArray("flights");
Gson gson = new Gson();
Type flightType = new TypeToken<List<Flight>>() {}.getType();
this.flights = gson.fromJson(String.valueOf(responseJSONArray), flightType);
}
As you can see, I'm kind of throwing it at the wall to see if it will stick. I'm trying to use Gson to get around some of the Type issues I've come across.
The error produced when executing is:
org.json.JSONException: Expected a ':' after a key at 7 [character 8 line 1]
Response String is as follows:
Response String Image
If that's difficult to deal with, here's the response in text:
INFO: {"FlightInfoResult":{"next_offset":-1,"flights":[{"ident":"N1RJ","aircrafttype":"HDJT","filed_ete":"01:25:00","filed_time":1593038253,"filed_departuretime":1593037500,"filed_airspeed_kts":400,"filed_airspeed_mach":"","filed_altitude":360,"route":"WEAZL4 CLAWD","actualdeparturetime":1593038285,"estimatedarrivaltime":1593043320,"actualarrivaltime":1593043320,"diverted":"","origin":"KJQF","destination":"KJXN","originName":"Concord-Padgett Rgnl","originCity":"Concord, NC","destinationName":"Jackson County","destinationCity":"Jackson, MI"},{"ident":"N1RJ","aircrafttype":"HDJT","filed_ete":"01:24:00","filed_time":1593000320,"filed_departuretime":1592998200,"filed_airspeed_kts":400,"filed_airspeed_mach":"","filed_altitude":350,"route":"PEGTE","actualdeparturetime":1593000420,"estimatedarrivaltime":1593005149,"actualarrivaltime":1593005149,"diverted":"","origin":"KJXN","destination":"KJQF","originName":"Jackson County","originCity":"Jackson, MI","destinationName":"Concord-Padgett Rgnl","destinationCity":"Concord, NC"},{"ident":"N1RJ","aircrafttype":"HDJT","filed_ete":"01:29:00","filed_time":1592518049,"filed_departuretime":1592513400,"filed_airspeed_kts":317,"filed_airspeed_mach":"","filed_altitude":360,"route":"WEAZL4 CLAWD","actualdeparturetime":1592517936,"estimatedarrivaltime":1592523120,"actualarrivaltime":1592523120,"diverted":"","origin":"KJQF","destination":"KJXN","originName":"Concord-Padgett Rgnl","originCity":"Concord, NC","destinationName":"Jackson County","destinationCity":"Jackson, MI"},{"ident":"N1RJ","aircrafttype":"HDJT","filed_ete":"01:24:00","filed_time":1592481020,"filed_departuretime":1592479800,"filed_airspeed_kts":319,"filed_airspeed_mach":"","filed_altitude":350,"route":"PEGTE","actualdeparturetime":1592481126,"estimatedarrivaltime":1592486100,"actualarrivaltime":1592486100,"diverted":"","origin":"KJXN","destination":"KJQF","originName":"Jackson County","originCity":"Jackson, MI","destinationName":"Concord-Padgett Rgnl","destinationCity":"Concord, NC"}]}}
There very well may be a much more simple way of accomplishing what I need. Any example help is very much appreciated.
You can use Gson string to object mapper class directly as like below,
package com.sample.programs;
import java.util.List;
import com.google.gson.Gson;
public class FlightInfoResultMain {
public static void main(String[] args) {
String input = "{\"FlightInfoResult\":{\"next_offset\":-1,\"flights\":[{\"ident\":\"N1RJ\",\"aircrafttype\":\"HDJT\",\"filed_ete\":\"01:25:00\",\"filed_time\":1593038253,\"filed_departuretime\":1593037500,\"filed_airspeed_kts\":400,\"filed_airspeed_mach\":\"\",\"filed_altitude\":360,\"route\":\"WEAZL4 CLAWD\",\"actualdeparturetime\":1593038285,\"estimatedarrivaltime\":1593043320,\"actualarrivaltime\":1593043320,\"diverted\":\"\",\"origin\":\"KJQF\",\"destination\":\"KJXN\",\"originName\":\"Concord-Padgett Rgnl\",\"originCity\":\"Concord, NC\",\"destinationName\":\"Jackson County\",\"destinationCity\":\"Jackson, MI\"},{\"ident\":\"N1RJ\",\"aircrafttype\":\"HDJT\",\"filed_ete\":\"01:24:00\",\"filed_time\":1593000320,\"filed_departuretime\":1592998200,\"filed_airspeed_kts\":400,\"filed_airspeed_mach\":\"\",\"filed_altitude\":350,\"route\":\"PEGTE\",\"actualdeparturetime\":1593000420,\"estimatedarrivaltime\":1593005149,\"actualarrivaltime\":1593005149,\"diverted\":\"\",\"origin\":\"KJXN\",\"destination\":\"KJQF\",\"originName\":\"Jackson County\",\"originCity\":\"Jackson, MI\",\"destinationName\":\"Concord-Padgett Rgnl\",\"destinationCity\":\"Concord, NC\"},{\"ident\":\"N1RJ\",\"aircrafttype\":\"HDJT\",\"filed_ete\":\"01:29:00\",\"filed_time\":1592518049,\"filed_departuretime\":1592513400,\"filed_airspeed_kts\":317,\"filed_airspeed_mach\":\"\",\"filed_altitude\":360,\"route\":\"WEAZL4 CLAWD\",\"actualdeparturetime\":1592517936,\"estimatedarrivaltime\":1592523120,\"actualarrivaltime\":1592523120,\"diverted\":\"\",\"origin\":\"KJQF\",\"destination\":\"KJXN\",\"originName\":\"Concord-Padgett Rgnl\",\"originCity\":\"Concord, NC\",\"destinationName\":\"Jackson County\",\"destinationCity\":\"Jackson, MI\"},{\"ident\":\"N1RJ\",\"aircrafttype\":\"HDJT\",\"filed_ete\":\"01:24:00\",\"filed_time\":1592481020,\"filed_departuretime\":1592479800,\"filed_airspeed_kts\":319,\"filed_airspeed_mach\":\"\",\"filed_altitude\":350,\"route\":\"PEGTE\",\"actualdeparturetime\":1592481126,\"estimatedarrivaltime\":1592486100,\"actualarrivaltime\":1592486100,\"diverted\":\"\",\"origin\":\"KJXN\",\"destination\":\"KJQF\",\"originName\":\"Jackson County\",\"originCity\":\"Jackson, MI\",\"destinationName\":\"Concord-Padgett Rgnl\",\"destinationCity\":\"Concord, NC\"}]}}";
System.out.println("input - " + input);
//Create Gson object
Gson gson = new Gson();
FlightInfoResultObject responseObject = gson.fromJson(input, FlightInfoResultObject.class);
// parsing response to java pojo
List<Flights> listOfFlights = responseObject.getFlightInfoResult().getFlights();
for (Flights flight : listOfFlights) {
System.out.println("flight - " + flight.getIdent());
}
}
}
Object Mapping class: Inside Flights.class you can add all the variable which you have in json response.
class FlightInfoResultObject {
FlightInfoResult FlightInfoResult;
#Getter
#Setter
}
class FlightInfoResult {
Integer next_offset;
List<Flights> flights;
#Getter
#Setter
}
class Flights {
String ident;
String aircrafttype;
#Getter
#Setter
}
I think it's impossible to retrieve the inner JSON element directly using gson.
You have to get FlightInfoResult then flights accordingly. This should work:
Gson gson = new Gson();
JsonObject jsonObject = com.google.gson.JsonParser.parseString(responseString).getAsJsonObject();
JsonArray flightArray = jsonObject.getAsJsonObject("FlightInfoResult").getAsJsonArray("flights");
Type flightType = new TypeToken<List<Flight>>() {}.getType();
List<Flight> flights = gson.fromJson(flightArray, flightType);
Anyway, make sure the name of all properties inside class Flight matches Json elements name, to avoid mapping errors.
Since you didn't post your Flight class definition and gson naming rule, but the Flight class should be like:
public class Flight {
private String ident;
private String aircrafttype;
private String filed_ete;
private float filed_time;
private float filed_departuretime;
private float filed_airspeed_kts;
private String filed_airspeed_mach;
private float filed_altitude;
private String route;
private float actualdeparturetime;
private float estimatedarrivaltime;
private float actualarrivaltime;
private String diverted;
private String origin;
private String destination;
private String originName;
private String originCity;
private String destinationName;
private String destinationCity;
// getters setters

Parse JSON Data using POJO, Where key name is numeric

I'm trying to parse a special JSON data using Wrapper class, special means a JSON which have numeric keys like below :
{
"date":"2018-11-01",
"hours":"01-Nov 08:00",
"1011":"837.7500",
"1022":"99.92596979567664",
"1010":"3.198083",
"1021":"5",
"1019":"1171.000",
"1018":"3.578371",
"1017":"30.46989",
"1016":"0.0001931423",
"1015":"6749",
"1014":"0.161805",
"1013":"0.001678397",
"1012":"1.406077"
}
I know how to parse JSON data using POJO, But in this case java is not accepting the numeric as Keys.
Wrapper/POJO Class
I don't want to go with JSON object based parsing. Is Anyone have any idea about it?
The Gson library has SerializedName functionality in which it parses the corresponding value of the key defined in SerializeName's parameter. Things will be tougher if your key is a pure integer since Java disallows it as variable name, in this case SerializeName will save you from that headache and it makes your code way more maintainable.
Example usage :
#SerializedName("1011") double lat;
#SerializedName("1022") double lng;
Try Gson for create wrapper class
http://www.jsonschema2pojo.org/
public class Example {
#SerializedName("date")
#Expose
private String date;
#SerializedName("hours")
#Expose
private String hours;
#SerializedName("1011")
#Expose
private String _1011;
#SerializedName("1022")
#Expose
private String _1022;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHours() {
return hours;
}
public void setHours(String hours) {
this.hours = hours;
}
public String get1011() {
return _1011;
}
public void set1011(String _1011) {
this._1011 = _1011;
}
public String get1022() {
return _1022;
}
public void set1022(String _1022) {
this._1022 = _1022;
}
Have a look at this code ,hope it works for you
JSONObject jsonObjectData = jsonObject1.getJSONObject("yourObject");
Iterator iterator = jsonObjectData.keys();
while (iterator.hasNext()) {
YourClass yourClass = new YourClass();
String key = (String) iterator.next();
yourClass.setKey(key);
yourClass.setVajue(jsonObjectData.getString(key));
yourList.add(yourClass);
}

How to convert JSON object using GSON in Java?

Here is the JSON string return from API:
{"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_image":"https:\/\/mydomain.com\/images\/eng\/promotion\/C199_MH.gif","error_message":{"eng":"","chi":""},"error_flags":""}
And I have created an object for this:
public class SummaryResponse {
String bps_id;
String bps_image;
String bps_message;
String as_of_date;
String bp_earned;
String bp_redeemed;
String bp_balance;
public String getBps_image() {
return bps_image;
}
public LangResponse getBps_message() {
return bps_message;
}
public String getAs_of_date() {
return as_of_date;
}
public String getBp_earned() {
return bp_earned;
}
public String getBp_redeemed() {
return bp_redeemed;
}
public String getBp_balance() {
return bp_balance;
}
}
It does not convert as expert, as there is some JSON object inside the string, how to convert that as well? Thanks for helping.
You can create like this,
public class SummaryResponse {
public String id;
public String bps_id;
public Summary summary;
public Message bps_message;
public String bps_image;
public Message error_message;
public String error_flags;
class Summary {
public String as_of_date;
public int bp_earned;
public String bp_balance;
public String bp_redeemed;
}
class Message {
public String eng;
public String chi;
}
}
you can call like this.
SummaryResponse summaryResponse = new Gson().fromJson([Your Json], SummaryResponse.class);
This a quick simple way to parse an array of Objects and also a single object it works for me when I am parsing json.
I believe it will only work as long as the json object is well formatted. I haven't experimented with a ill-formatted json object but that is because the api it request from was build by me, so I haven't had to worry about that
Gson gson = new Gson();
SummaryResponse[] data = gson.fromJson(jsonObj, SummaryResponse[].class);

Convert java object in JSON

I'm trying to convert a simple java object in JSON. I'm using google Gson library and it works, but I want a complete JSON object in this form:
{"Studente":[{ "nome":"John", "cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
This is my class:
public class Studente {
private String nome;
private String cognome;
private String matricola;
private String dataNascita;
public Studente(){
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getDataNascita() {
return dataNascita;
}
public void setDataNascita(String dataNascita) {
this.dataNascita = dataNascita;
}
}
This is tester:
Studente x = new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson = new Gson();
String toJson = gson.toJson(x, Studente.class);
System.out.println("ToJSON "+toJson);
I have this in toJson: {"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}
The Json that you are trying to achieve is not the representation of a single Studente object, it is the representation of an object containing a list of Studente objects, that has a single entry.
So, you would need to create that extra object that contains the list of Studente objects, add the one instance to the list, and then serialize the object containing the list.
There's one minor issue, though. You are essentially asking for the wrapper object's list to have a property name that starts with a capital letter. This can be done, but breaks Java coding conventions.
It is best to write a wrapper for Students list. like this:
import java.util.ArrayList;
public class StudentWrapper {
private ArrayList<Studente> studente;
public StudentWrapper() {
studente = new ArrayList<Studente>();
}
public void addStudent(Studente s){
studente.add(s);
}
}
Code to convert to JSON :
Studente x=new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson=new Gson();
StudentWrapper studentWrapper = new StudentWrapper();
studentWrapper.addStudent(x);
String toJson=gson.toJson(studentWrapper, StudentWrapper.class);
System.out.println("ToJSON "+toJson);
The output will be like this. The way you want it.
ToJSON {"studente":[{"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}

Converting LinkedHashMap<String,MyClass> to Java Object

How can I convert the JSON string like this:
{ "summary": {
"totalMR":4.599000000000903E12,
"totalMA":1.9174920000386694E11,
"totalQA":5.1111111181E9,
"totalQR":1.000020666115264E11
},
"result": [{},{}],
"success":"true",
"total":49
}
to a Java object. I went through many similar posts and implemented constructors but couldn't find the proper explanation of why I'm unable to De-serialize the JSON.
Am I doing anything wrong?
My Class:
public class expResponse {
private String success;
private String total;
private ArrayList<LinkedHashMap<String,Object>> result;
private LinkedHashMap<String,SummaryResponse> summary;
// Constructor: public expResponse(){}
// Getter and Setter
}
public class SummaryResponse {
private Float totalQR;
private Float totalQA;
private Float totalMR;
private Float totalMA;
public SummaryResponse(){}
// Setter and Getter
}
My Code:
private expResponse processResult(String result) throws IOException{
ObjectMapper objectMapper = new ObjectMapper();
expResponse expResponseObj =
objectMapper.readValue(result, expResponse.class);
return expResponseObj;
The json you posted would not deserialize into a map of SummaryResponse objects, but rather an individual SummaryResponse object. To make your binding work, you would have to have json that looked something like this:
{
...
'summary': {
'summary1': {"totalMR":4.599000000000903E12,"totalMA":1.9174920000386694E11,"totalQA":5.1111111181E9,"totalQR":1.000020666115264E11}
'summary2': {"totalMR":4.599000000000903E12,"totalMA":1.9174920000386694E11,"totalQA":5.1111111181E9,"totalQR":1.000020666115264E11}
}
...
}
Alternatively, if you need to make your Java class conform to the json you provided, you simply need to change the declaration of summary:
private SummaryResponse summary;
Field summary in your json is an object of type SummaryResponse and not a LinkedHashMap.
public class ExpResponse {
private String success;
private String total;
private ArrayList<LinkedHashMap<String,Object>> result;
private Summary summary;
}
I don't think you have a problem in the code. Your input fails because it is not in the correct format. If you try to write the same values from an object with the same values to string you get something like:
{
"success":"true",
"total":"49",
"result":null,
"summary":{
"one_summary":{
"totalQR":2000.0,
"totalQA":1500.0,
"totalMR":1000.0,
"totalMA":500.0
}
}
}
And the major difference is the one summary. This is because summary is a map and maps need a key for each entryset. That means that summary is your map which has a one_summary key.
Is it the SummaryResponse that can't be deserialised?
I guess your attributes should have the same name "totalMR", "totalMA"....
or you should use an annotation JsonProperty(value="totalMR") and so on.

Categories

Resources