I can't get data of object in json - java

I have json file with an object
{
"id": 387,
"name": "flatFive",
"coordinates": {
"x": 9.6,
"y": 2.2
},
"creationDate": {
"year": 2020,
"monthValue": 4,
"month": "APRIL",
"dayOfMonth": 1,
"dayOfYear": 92,
"dayOfWeek": "WEDNESDAY",
"hour": 20,
"minute": 40,
"second": 47,
"nano": 662000000,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
},
"area": 332.3,
"numberOfRooms": 3,
"furnish": "bad",
"view": "NORMAL",
"transport": "NONE",
"house": {
"name": "Cottage",
"year": 3,
"numberOfLifts": 6
}
so, how can I get data "x" or "y" for example from "coordinates"? or "name" and "year" from "house"?
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("ff.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
JSONObject coor = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
Long id = (Long) person.get("id");
System.out.println(id);
Double area = (Double) person.get("area");
System.out.println(area);
Coordinates oor = (Coordinates) person.get("coordinates");
System.out.println(person.get("oor"));
I tried to do this but I get exception
"
flatFive
387
332.3
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to Coordinates"

I think using jackson for this would be a better approach. Something like this:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class Parse {
public static void main(String[] args) {
parse("{\n" + " \"id\":387,\n" + " \"name\":\"flatFive\",\n" + " \"coordinates\":{\n" + " \"x\":9.6,\n" + " \"y\":2.2\n" + " },\n" + " \"creationDate\":{\n" + " \"year\":2020,\n" + " \"monthValue\":4,\n" + " \"month\":\"APRIL\",\n" + " \"dayOfMonth\":1,\n" + " \"dayOfYear\":92,\n" + " \"dayOfWeek\":\"WEDNESDAY\",\n" + " \"hour\":20,\n" + " \"minute\":40,\n" + " \"second\":47,\n" + " \"nano\":662000000,\n" + " \"chronology\":{\n" + " \"id\":\"ISO\",\n" + " \"calendarType\":\"iso8601\"\n" + " }\n" + " },\n" + " \"area\":332.3,\n" + " \"numberOfRooms\":3,\n" + " \"furnish\":\"bad\",\n" + " \"view\":\"NORMAL\",\n" + " \"transport\":\"NONE\",\n" + " \"house\":{\n" + " \"name\":\"Cottage\",\n" + " \"year\":3,\n" + " \"numberOfLifts\":6\n" + " }\n" + "}");
}
public static void parse(String url) {
Destination destination = (Destination) convertBodyToObject(url, Destination.class);
System.out.println(destination.getId());
System.out.println(destination.getCoordinates().getX());
System.out.println(destination.getCoordinates().getY());
System.out.println(destination.getHouse().getName());
System.out.println(destination.getHouse().getYear());
}
public static Object convertBodyToObject(String body, Class object) {
try {
return new ObjectMapper().readValue(body, object);
} catch (JsonGenerationException e) {
System.out.println("JsonGenerationException - Failed to convertBodyToObject() " + e);
} catch (JsonMappingException e) {
System.out.println("JsonMappingException - Failed to convertBodyToObject() " + e);
} catch (IOException e) {
System.out.println("IOException - Failed to convertBodyToObject() " + e);
}
throw new RuntimeException("Terminating... " + body + " couldn't be mapped correctly");
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Destination {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private Coordinates coordinates;
private House house;
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public House getHouse() {
return house;
}
public void setHouse(House house) {
this.house = house;
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class House {
private String name;
private Integer year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Coordinates {
private Double x;
private Double y;
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
}

Related

How to fix 'JsonSyntaxException' at Date conversion

I am working on a Project which imports data into a Webservice via HTTPS POST Requests. In order to create HTTPS Requests I am using Retrofit2.
This is my approach on how to create the request and evaluate the response:
I am creating an Object where I store my information
I call a method of the Object which converts the data into a proper format for the request (JSON Format)
I create the Retrofit Client and make a call.
The last point is evaluating the Response (at this point it skips the onResponse() method and enters the onFailure() method with JsonSyntaxException
I've already tried a DateDeserializer... Unfortunately without any results
This is the format of the Request:
tokenid=ABCDEFG
&bookuser=testuser
&input= {
"0": {
"ISSUEKEY": "ABC-81",
"STARTDATE": "15.12.2016 09:00",
"ENDDATE": "15.12.2016 11:30",
"BOOKINGTEXT": "Testeintrag 1. Stephan Perner ISSUEKEY, ohne Sekunden"
},
"1": {
"ISSUEKEY": "ABC-82",
"STARTDATE": "15.12.2016 12:00",
"ENDDATE": "15.12.2016 17:45",
"BOOKINGTEXT": "Testeintrag 2. Stephan Perner, ohne Sekunden"
}
}
This is the method which will be called when I press a Button in order to start the sending process:
w.setBookingtext("testeintrag#2");
System.out.println("String: " + w.toRequest());
String token = loadToken();
Log.e(TAG, token);
Call call = jiraService.postWorktime(token, "mschwar", "{\"0\":" + w.toRequest() + "}");
This is the Call of the Retrofit Library which I created in order to fill the Body of the POST Request:
#POST("postWorktime")
Call<PostWorkTimeResponse> postWorktime(#Field("tokenid") String token, #Field("bookuser") String bookuser, #Field("input") String input);
This is the POJO:
import com.google.gson.annotations.SerializedName;
import org.json.JSONObject;
import java.sql.SQLOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Worktime
{
#SerializedName("ISSUEKEY")
private String projectKey;
#SerializedName("STARTDATE")
private Date from;
#SerializedName("ENDDATE")
private Date to;
#SerializedName("BOOKINGTEXT")
private String bookingtext;
public Worktime(Date from, Date to, String projectKey) {
this.from = from;
this.to = to;
this.projectKey = projectKey;
}
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
public String getProjectKey() {
return projectKey;
}
public void setProjectKey(String projectKey) {
this.projectKey = projectKey;
}
public String getBookingtext() {
return bookingtext;
}
public void setBookingtext(String bookingtext) {
this.bookingtext = bookingtext;
}
#Override
public String toString() {
return "Worktime{" +
"from=" + from +
", to=" + to +
", projectKey='" + projectKey + '\'' +
", bookingtext='" + bookingtext + '\'' +
'}';
}
public String toRequest()
{
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY);
Date dStart = from;
Date dEnd = to;
dEnd.setHours(15);
return String.format("{" +
"\"ISSUEKEY\":\"%s\"," +
"\"STARTDATE\":\"%s\"," +
"\"ENDDATE\":\"%s\"," +
"\"BOOKINGTEXT\":\"%s\"" +
"}", projectKey, df.format(dStart), df.format(dEnd), bookingtext);
}
}
And this is the class where I implemented the Callback interface:
package com.ssi.zeiterfassungsapp.webservice;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ssi.zeiterfassungsapp.beans.PostWorkTimeRelated.PostWorkTimeResponse;
import com.ssi.zeiterfassungsapp.util.AsyncDelegate;
import java.lang.reflect.Type;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class WorktimeImporter implements Callback
{
private static final String TAG = "WorktimeImporter";
private Context mContext;
private AsyncDelegate delegate;
private Gson gson;
public WorktimeImporter(Context mContext, AsyncDelegate delegate) {
this.mContext = mContext;
this.delegate = delegate;
gson = new GsonBuilder().setLenient().serializeNulls().setDateFormat("dd.MM.yyyy HH:mm").create();
}
#Override
public void onResponse(Call call, Response response) {
Type type = new TypeToken<PostWorkTimeResponse>(){}.getType(); //Creates instance of the Type (PostWorkTimeResponse)
PostWorkTimeResponse workTimeResponse = null;
Log.e(TAG, "Error in onResponse()");
if(response.code() == 200){
workTimeResponse = (PostWorkTimeResponse) response.body();
}else
{
try {
workTimeResponse = gson.fromJson(response.errorBody().string(), type); //Converts the response to LoginResponse
Log.e(TAG, response.errorBody().string());
} catch (Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
}
}
Log.e(TAG, workTimeResponse.toString());
}
#Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
}
And this is the result of printStackTrace():
W/System.err: com.google.gson.JsonSyntaxException: 15.07.2019 12:48
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:74)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:59)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:41)
W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
W/System.err: at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: java.text.ParseException: Failed to parse date ["15.07.2019 12:48']: Invalid number: 15.0
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:72)
... 18 more
Caused by: java.lang.NumberFormatException: Invalid number: 15.0
at com.google.gson.internal.bind.util.ISO8601Utils.parseInt(ISO8601Utils.java:318)
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:129)
... 19 more
I hope somebody can help me with this issue, I am relatively new to Retrofit and making Requests to Webservices. Thank you in advance, I would really appreciate some help
The response of the Request should look like that:
{
"status": "Ok",
"token": "ABCDEFG",
"user": "testuser",
"origin": "XXX",
"target": "IF",
"bookuser": "testuser",
"booking":
{
0:
{
"ISSUEKEY": "ABC-81",
"STARTDATE": "15.12.2016 09:00",
"ENDDATE": "15.12.2016 11:30",
"BOOKINGTEXT": "Testeintrag 1. Stephan Perner auf korrekten ISSUEKEY, ohne Sekunden"
}
,
1:
{
"ISSUEKEY": "ABC-82",
"STARTDATE": "15.12.2016 12:00",
"ENDDATE": "15.12.2016 17:45",
"BOOKINGTEXT": "Testeintrag 2. Stephan Perner auf korrekten ISSUEKEY, ohne Sekunden"
}
}
}
You can update your pojo like below
public class Worktime
{
#SerializedName("ISSUEKEY")
private String projectKey;
#SerializedName("STARTDATE")
private String from;
#SerializedName("ENDDATE")
private String to;
#SerializedName("BOOKINGTEXT")
private String bookingtext;
public Worktime(String from, String to, String projectKey) {
this.from = from;
this.to = to;
this.projectKey = projectKey;
}
public String getFrom() {
return from;
}
public String getFromAsDate() {
try {
return new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY).parse(from);
} catch (Exception e) {
}
return null;
}
public void setFrom(Date from) {
this.from = from;
}
public String getTo() {
return to;
}
public String getToAsDate() {
try {
return new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY).parse(to);
} catch (Exception e) {
}
return null;
}
public void setTo(String to) {
this.to = to;
}
public String getProjectKey() {
return projectKey;
}
public void setProjectKey(String projectKey) {
this.projectKey = projectKey;
}
public String getBookingtext() {
return bookingtext;
}
public void setBookingtext(String bookingtext) {
this.bookingtext = bookingtext;
}
#Override
public String toString() {
return "Worktime{" +
"from=" + from +
", to=" + to +
", projectKey='" + projectKey + '\'' +
", bookingtext='" + bookingtext + '\'' +
'}';
}
public String toRequest()
{
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY);
Date dStart = from;
Date dEnd = to;
dEnd.setHours(15);
return String.format("{" +
"\"ISSUEKEY\":\"%s\"," +
"\"STARTDATE\":\"%s\"," +
"\"ENDDATE\":\"%s\"," +
"\"BOOKINGTEXT\":\"%s\"" +
"}", projectKey, df.format(dStart), df.format(dEnd), bookingtext);
}
}
You can get startdate and enddate as object from getFromAsDate() and getToAsDate()

I can't parse a Json file to a java object using Gson

I have a Json file like this:
{
"airports": [
{
"fs": "VGO",
"iata": "VGO",
"icao": "LEVX",
"name": "Vigo Airport",
"city": "Vigo",
"cityCode": "VGO",
"stateCode": "SP",
"countryCode": "ES",
"countryName": "Spain and Canary Islands",
"regionName": "Europe",
"timeZoneRegionName": "Europe/Madrid",
"localTime": "2018-01-29T08:59:15.661",
"utcOffsetHours": 1,
"latitude": 42.224551,
"longitude": -8.634025,
"elevationFeet": 860,
"classification": 4,
"active": true,
"weatherUrl": "https://api.flightstats.com/flex/weather/rest/v1/json/all/VGO?codeType=fs",
"delayIndexUrl": "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/VGO?codeType=fs"
}
]
}
and I want to use to create an airport object.
public class Airport {
String iata;
String name;
String city;
String countryName;
String regionName;
String timeZoneRegionName;
double utcOffsetHours;
double latitude;
double longitude;
int elevationFeet;
#Override
public String toString() {
return "Airports{" +
"iata='" + iata + '\'' +
", name='" + name + '\'' +
", city='" + city + '\'' +
", countryName='" + countryName + '\'' +
", regionName='" + regionName + '\'' +
", timeZoneRegionName='" + timeZoneRegionName + '\'' +
", utcOffsetHours=" + utcOffsetHours +
", latitude=" + latitude +
", longitude=" + longitude +
", elevationFeet=" + elevationFeet +
'}';
}
}
and I read it in the following way:
public void imprimirJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
But if I execute this code, the Log prints an empty array
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
I think that the problem is that the first attribute, has an array of the info that I want. But I don't know how to access the info. Can you show me the way?
create a class MyAirports.java.
public class MyAirports{
List<Airport> airports;
public List<Airport> getAirportList()
{
return this.airports;
}
}
and do,
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
MyAirports airports = null;
try {
//airport = gson.fromJson(new FileReader(filePath), Airport.class);
airports = gson.fromJson(new FileReader(filePath), MyAirports.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airports.getAirportList().get(0).toString());
}
The value of "airports" in your json file is a JsonArray. Hence, you can implement like this:
public void imprimirJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport[] airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport[].class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
Later, airport[0] is what you want to print out.

Gson to parse string of arrays

I need to parse the below JSON content. Currently I have stored it inflat file and reading it. I have given the sample POJO classes which are created and the code which I tried below.
Tried two different approach and both are giving the following error
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $
Json file
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
POJO classes:
Note: I have mentioned only two classes here.
package com.As.jsonmodel.configrequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class ConfigurationRequest
{
private DeviceList[] DeviceList;
private DeviceCommon DeviceCommon;
public DeviceList[] getDeviceList ()
{
return DeviceList;
}
public void setDeviceList (DeviceList[] DeviceList)
{
this.DeviceList = DeviceList;
}
public DeviceCommon getDeviceCommon ()
{
return DeviceCommon;
}
public void setDeviceCommon (DeviceCommon DeviceCommon)
{
this.DeviceCommon = DeviceCommon;
}
#Override
public String toString()
{
return "ClassPojo [DeviceList = "+DeviceList+", DeviceCommon = "+DeviceCommon+"]";
}
}
package com.As.jsonmodel.configrequest;
public class DeviceList
{
private MobileOriginatorCallbackReference MobileOriginatorCallbackReference;
private String NIDDduration;
private String ASreferenceID;
private String senderName;
private String ExternalIdentifer;
private String msisdn;
private ConfigurationResultCallbackReference ConfigurationResultCallbackReference;
public MobileOriginatorCallbackReference getMobileOriginatorCallbackReference ()
{
return MobileOriginatorCallbackReference;
}
public void setMobileOriginatorCallbackReference (MobileOriginatorCallbackReference MobileOriginatorCallbackReference)
{
this.MobileOriginatorCallbackReference = MobileOriginatorCallbackReference;
}
public String getNIDDduration ()
{
return NIDDduration;
}
public void setNIDDduration (String NIDDduration)
{
this.NIDDduration = NIDDduration;
}
public String getASreferenceID ()
{
return ASreferenceID;
}
public void setASreferenceID (String ASreferenceID)
{
this.ASreferenceID = ASreferenceID;
}
public String getSenderName ()
{
return senderName;
}
public void setSenderName (String senderName)
{
this.senderName = senderName;
}
public String getExternalIdentifer ()
{
return ExternalIdentifer;
}
public void setExternalIdentifer (String ExternalIdentifer)
{
this.ExternalIdentifer = ExternalIdentifer;
}
public String getMsisdn ()
{
return msisdn;
}
public void setMsisdn (String msisdn)
{
this.msisdn = msisdn;
}
public ConfigurationResultCallbackReference getConfigurationResultCallbackReference ()
{
return ConfigurationResultCallbackReference;
}
public void setConfigurationResultCallbackReference (ConfigurationResultCallbackReference ConfigurationResultCallbackReference)
{
this.ConfigurationResultCallbackReference = ConfigurationResultCallbackReference;
}
#Override
public String toString()
{
return "ClassPojo [MobileOriginatorCallbackReference = "+MobileOriginatorCallbackReference+", NIDD duration = "+NIDDduration+", AS referenceID = "+ASreferenceID+", senderName = "+senderName+", ExternalIdentifer = "+ExternalIdentifer+", msisdn = "+msisdn+", ConfigurationResultCallbackReference = "+ConfigurationResultCallbackReference+"]";
}
}
Json Reader
Approach1:
BufferedReader br = null;
try {
br = new BufferedReader(
new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonReader jsonReader = new JsonReader(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("DeviceCommon")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("ASIdentifier")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("MobileOriginatorCallbackReference")){
System.out.println(jsonReader.nextString());
}
if (n.equals("AccessiblityCallbackReference")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("DeviceList")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
// TODO Auto-generated method stub
Aproach2:
Gson gson = new Gson();
DeviceList [] myTypes = gson.fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), DeviceList[].class);
System.out.println(gson.toJson(myTypes));
Any pointers on how to parse this file will be helpful.
Here's how to do it with Gson:
import java.io.FileReader;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class Main {
public static void main(String[] args) throws Exception {
Data data = new Gson().fromJson(new FileReader("data.json"), Data.class);
System.out.println(data);
}
}
class Data {
#SerializedName("DeviceCommon")
DeviceCommon deviceCommon;
#SerializedName("DeviceList")
DeviceListEntry[] deviceList;
#Override
public String toString() {
return "Data{" +
"\n deviceCommon=" + deviceCommon +
"\n deviceList=" + Arrays.toString(deviceList) +
"\n}";
}
}
class DeviceCommon {
#SerializedName("ASIdentifier")
String asIdentifier;
#SerializedName("DatadeliveyMechanism")
String datadeliveyMechanism;
#SerializedName("MobileOriginatorCallbackReference")
Url mobileOriginatorCallbackReference;
#SerializedName("AccessiblityCallbackReference")
Url accessiblityCallbackReference;
#Override
public String toString() {
return "DeviceCommon{" +
"\n asIdentifier='" + asIdentifier + '\'' +
"\n datadeliveyMechanism='" + datadeliveyMechanism + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n accessiblityCallbackReference=" + accessiblityCallbackReference +
"\n }";
}
}
class DeviceListEntry {
#SerializedName("ExternalIdentifer")
String externalIdentifer;
String msisdn;
String senderName;
#SerializedName("MobileOriginatorCallbackReference")
NotifyUrl mobileOriginatorCallbackReference;
#SerializedName("ConfigurationResultCallbackReference")
NotifyUrl configurationResultCallbackReference;
#SerializedName("ASreferenceID")
String asReferenceID;
#SerializedName("NIDDduration")
String nidDduration;
#Override
public String toString() {
return "DeviceListEntry{" +
"\n externalIdentifer='" + externalIdentifer + '\'' +
"\n msisdn='" + msisdn + '\'' +
"\n senderName='" + senderName + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n configurationResultCallbackReference=" + configurationResultCallbackReference +
"\n asReferenceID='" + asReferenceID + '\'' +
"\n nidDduration='" + nidDduration + '\'' +
"\n }";
}
}
class Url {
String url;
#Override
public String toString() {
return url;
}
}
class NotifyUrl {
String notifyURL;
#Override
public String toString() {
return notifyURL;
}
}
Running Main will result in the following output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}

Java JSON weird error

When I run my program I am getting the error:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.<init>(JSONObject.java:184)
at MovieLibrary.<init>(MovieLibrary.java:76)
at LibraryOfMovieDescriptions.main(LibraryOfMovieDescriptions.java:11)
Also, once I run the program, I check how my "movies2.json" has changed because that's the one I'm writing to to save the file, and it changes from initially only the file being { } to the file then being ’ t {}
I don't how I end up getting that in "movies2.json".
"movies.json", the file being used in the MovieLibrary constructor is this:
{ "Minions Puppy": {
"Released": "10 Dec 2013",
"Rated": "NR",
"Actors": ["Dave", "Gru"],
"Plot": "Dave seeing many owners walk their dogs wants a puppy of his own. He finds a mini-UFO who becomes his pal. This short film released with Despicable Me 2 chronicles how Dave helps the UFO return home.",
"Runtime": "4:16 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsPuppy.mp4",
"Title": "Minions Puppy"
},
"Pretty Woman": {
"Released": "10 Dec 1973",
"Rated": "NR",
"Actors": ["Roy Orbison"],
"Plot": "One of Roys most famous songs.",
"Runtime": "3 min",
"Genre": ["Country Music"],
"Filename": "RoyOrbisonPrettyWoman.mp4",
"Title": "Pretty Woman"
},
"Minions Banana Song": {
"Released": "12 Dec 2015",
"Rated": "PG",
"Actors": ["Steve", "Kevin", "Bob", "Stuart"],
"Plot": "Banana is a song sung by The Minions in the teaser trailer of Despicable Me 2. It is a parody of the Beach Boys Barbara Ann. One minion gets annoyed by another, most likely Stuart, who keeps on playing his party horn while they are singing. So, at the end, he punched Stuart.",
"Runtime": "5 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsBananaSong.mp4",
"Title": "Minions Banana Song"
},
"Minions Banana": {
"Released": "12 Dec 2015",
"Rated": "PG",
"Actors": ["Steve", "Kevin", "Stuart"],
"Plot": "Minions fight over a banana. In the process, they wreak havoc in the Bomb Factory.",
"Runtime": "5 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsBanana.mp4",
"Title": "Minions Banana"
},
"Squatters Rights": {
"Released": "07 Jun 1946",
"Rated": "N/A",
"Actors": ["Dessie Flynn", "James MacDonald"],
"Plot": "Chip-n-Dale have set up house in the wood stove of Mickeys cabin. Pluto knows they are there, but Mickey only knows his matches keep going out when he tries to light a fire.",
"Runtime": "7 min",
"Genre": ["Cartoon", "Animation", "Family"],
"Filename": "MMSquattersRights.mp4",
"Title": "Squatters Rights"
}
}
So I would really love any help or explanation. Thanks in advance.
Here is the code:
MAIN CLASS
import java.io.Serializable;
class LibraryOfMovieDescriptions implements Serializable {
public static void main(String[] args){
MovieLibrary movieLibrary;
movieLibrary = new MovieLibrary("movies.json");
movieLibrary.toJsonFile("movies2.json");
}
}
MovieDescription Class
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.Serializable;
public class MovieDescription implements Serializable {
private String title;
private String rating;
private String release;
private String runtime;
private String plot;
private String filename;
private String genre;
private String actors;
public JSONObject toJSONObject() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("Title", title);
obj.put("Rated", rating);
obj.put("Released", release);
obj.put("Runtime", runtime);
obj.put("Plot", plot);
obj.put("Filename", filename);
JSONArray a = new JSONArray();
String[] sArray = this.actors.split(" , ");
for(int i = 0; i < sArray.length; i++){
a.put(i);
}
obj.put("Actors", a);
JSONArray g = new JSONArray();
String[] gArray = this.genre.split(" , ");
for(int i = 0; i < gArray.length; i++){
g.put(i);
}
obj.put("Genre", g);
return obj;
}
public MovieDescription(JSONObject jsonObj) throws JSONException{
this.title = jsonObj.getString("Title");
this.rating = jsonObj.getString("Rated");
this.release = jsonObj.getString("Released");
this.plot = jsonObj.getString("Plot");
this.runtime = jsonObj.getString("Runtime");
this.filename = jsonObj.getString("Filename");
JSONArray g = jsonObj.getJSONArray("Genre");
for(int i = 0; i < g.length(); i++){
this.genre += g.get(i) + ", ";
}
JSONArray a = jsonObj.getJSONArray("Actors");
for(int i = 0; i < a.length(); i++){
this.actors += a.get(i) + ", ";
}
}
public MovieDescription(){
title = " ";
rating = " ";
release = " ";
runtime = " ";
plot = " ";
filename = " ";
genre = " ";
actors = " ";
}
public MovieDescription(String title, String rating, String release, String runtime, String plot, String filename,
String genre, String actors){
this.title = title;
this.rating = rating;
this.release = release;
this.runtime = runtime;
this.plot = plot;
this.filename = filename;
this.genre = genre;
this.actors = actors;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return title;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setRelease(String release){
this.release = release;
}
public String getRelease(){
return this.release;
}
public void setRuntime(String runtime){
this.runtime = runtime;
}
public String getRuntime(){
return runtime;
}
public void setPlot(String plot){
this.plot = plot;
}
public String getPlot(){
return plot;
}
public void setFilename(String filename){
this.filename = filename;
}
public String getFilename(){
return filename;
}
public void setGenre(String genre){
this.genre = genre;
}
public String getGenre(){
return genre;
}
public void setActors(String actors){
this.actors = actors;
}
public String getActors(){
return actors;
}
public String toString(){
String string = ("Title: " + title + "\n" + "Rating: " + rating + "\n" + "Released: " + release + "\n" +
"Runtime: " + runtime + "\n" + "Plot: " + plot + "\n" + "Filename: " + filename + "\n" + "Genre: " + genre
+ "\n" + "Actors: " + actors + "\n");
return string;
}
}
MovieLibrary Class
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.json.JSONTokener;
import java.io.Serializable;
import java.io.ObjectOutputStream;
public class MovieLibrary implements Serializable {
private List<MovieDescription> movieLib = new ArrayList<MovieDescription>();
private int arraySize;
public MovieLibrary(){
arraySize = 0;
}
public boolean isEmpty(){
return arraySize == 0;
}
public MovieDescription get(String aTitle){
int i = indexOf(aTitle);
if(i == -1){
return null;
}
return movieLib.get(i);
}
public boolean add(MovieDescription aClip){
movieLib.add(aClip);
arraySize++;
return true;
}
public boolean remove(String aTitle){
int i = indexOf(aTitle);
if(i != -1){
movieLib.remove(i);
arraySize--;
}
return true;
}
public String[] getTitles(){
String[] s = new String[movieLib.size()];
for(int i = 0; i < movieLib.size(); i++){
s[i] = movieLib.get(i).getTitle();
}
return s;
}
private int indexOf(String aTitle){
for(int i = 0; i < movieLib.size(); i++)
if(((movieLib.get(i)).getTitle()).equals(aTitle)){
return i;
}
return -1;
}
public MovieLibrary(String jsonFile){
FileInputStream in = null;
JSONObject jsonObj = null;
String[] titles;
try{
in = new FileInputStream(jsonFile);
jsonObj = new JSONObject(new JSONTokener(in));
titles = JSONObject.getNames(jsonObj);
System.out.println("Adding Movies...");
for(int i = 0; i < titles.length; i++){
System.out.println(titles[i]);
JSONObject temp = jsonObj.getJSONObject(titles[i]);
MovieDescription movies = new MovieDescription(temp);
movieLib.add(movies);
}
System.out.println(movieLib);
in.close();
}
catch(Exception e){
e.printStackTrace();
if(in != null){
try{
in.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
public void toJsonFile(String jsonFileName){
JSONObject jsonObj = new JSONObject();
ObjectOutputStream out = null;
try{
for(int i = 0; i < movieLib.size(); i++)
jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject());
out = new ObjectOutputStream(new FileOutputStream(jsonFileName));
out.writeObject(jsonObj.toString());
out.close();
}
catch(Exception e){
e.printStackTrace();
if(out != null){
try{
out.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
}
You don't want to use an ObjectOutputStream to write text. It's writing a serialized Java string and that explains the weird characters at the start of your file. Try using a FileWriter instead.
public void toJsonFile(String jsonFileName) {
JSONObject jsonObj = new JSONObject();
FileWriter out = null;
try{
for(int i = 0; i < movieLib.size(); i++)
jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject());
out = new FileWriter(jsonFileName);
out.write(jsonObj.toString());
out.close();
}
catch(Exception e){
e.printStackTrace();
if(out != null){
try{
out.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
P.S. You might also change your try/catch block to a try-with-resources statement.

Parse List of JSON objects using GSON

I have a JSON object like this:
{
"user1": {
"timeSpent": "20.533333333333335h",
"worklog": [
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-2",
"comment": "\ncccccc",
"timeSpent": "20.533333333333335h"
}
],
"dayTotal": "20.533333333333335h"
}
]
},
"admin": {
"timeSpent": "601.1h",
"worklog": [
{
"date": "06/25/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "113.1h"
}
],
"dayTotal": "113.1h"
},
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "8h"
},
{
"issueCode": "COC-2",
"comment": "",
"timeSpent": "480h"
}
],
"dayTotal": "488h"
}
]
}
}
and trying to parse it with Gson:
Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);
But the 'responceBean' is always 'null'
Here are all the other classes:
public class Book {
private List<User> user = new LinkedList<User>();
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new LinkedList<WorkLog>();;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklogs(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
}
public class WorkLog{
private String date;
private String dayTotal;
private List<Issues> issues;
public String getDate(){
return this.date;
}
public void setDate(String date){
this.date = date;
}
public String getDayTotal(){
return this.dayTotal;
}
public void setDayTotal(String dayTotal){
this.dayTotal = dayTotal;
}
public List<Issues> getIssues(){
return this.issues;
}
public void setIssues(List<Issues> issues){
this.issues = issues;
}
}
public class Issues{
private String comment;
private String issueCode;
private String timeSpent;
public String getComment(){
return this.comment;
}
public void setComment(String comment){
this.comment = comment;
}
public String getIssueCode(){
return this.issueCode;
}
public void setIssueCode(String issueCode){
this.issueCode = issueCode;
}
public String getTimeSpent(){
return this.timeSpent;
}
public void setTimeSpent(String timeSpent){
this.timeSpent = timeSpent;
}
}
This is my latest attempt. Somehow I cannot figure out the right way. Will be very appreciative for any help.
Your JSON model does not match your object model.
You need an intermediate layer to fill the gap: a TypeAdapter.
Moreover there is no naming information for the user.
And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is a fixed version:
Java model:
class User {
private String timeSpent;
#SerializedName("worklog")
private List<WorkLog> worklogs = new LinkedList<WorkLog>();
private String name;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklog(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The plumbing to fill the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book>
{
Gson gson = new Gson();
public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context)
{
JsonObject json = new JsonObject();
for (User user : book.getUser())
{
json.addProperty(user.getName(), gson.toJson(user));
}
return json;
}
public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject json = element.getAsJsonObject();
Book book = new Book();
for (Entry<String, JsonElement> entry : json.entrySet())
{
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(), User.class);
user.setName(name);
book.getUser().add(user);
}
return book;
}
}
And a roundtrip:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTypeAdapter());
Gson gson = builder.create();
Book book = gson.fromJson("{" +
" \"user1\": {" +
" \"timeSpent\": \"20.533333333333335h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\ncccccc\"," +
" \"timeSpent\": \"20.533333333333335h\"" +
" }" +
" ]," +
" \"dayTotal\": \"20.533333333333335h\"" +
" }" +
" ]" +
" }," +
" \"admin\": {" +
" \"timeSpent\": \"601.1h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/25/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"113.1h\"" +
" }" +
" ]," +
" \"dayTotal\": \"113.1h\"" +
" }," +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"8h\"" +
" }," +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"480h\"" +
" }" +
" ]," +
" \"dayTotal\": \"488h\"" +
" }" +
" ]" +
" }" +
"}", Book.class);
String json = gson.toJson(book);
Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson
Enjoy! :)
I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new List < WorkLog >();
}
Try this and I hope that it will help.
P.S.
Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.

Categories

Resources