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()
Related
I looked at some other threads about this topic and integrated the solution it offered but it still throws the same error. this is the first time i try to call an api on android. here i want to 'GET' an array of objects. There is no stack trace since the app does not crash. i think the problem has to do with the array of questions.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.100:3000/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts){
String content = "";
content += "Doctor: " + post.getDoctor() + "\n";
content += "Name: " + post.getName() + "\n";
content += "Questions: " + post.getQuestions() + "\n\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
here is an example of the json data:
[
{
"questions":[...],
"_id":"5f42954a7e252b48ec3564b6",
"name":"Lifestyle",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f4299687e252b48ec3564b7",
"name":"Headache",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f429b2f7e252b48ec3564b9",
"name":"Foot pain",
"doctor":"doctoremail#gmail.com",
"__v":0
}
]
I fixed it. the problem was that the 'questions' property in my model was of type string in stead of List String
package com.example.medlog;
import java.util.List;
public class Post {
private String name;
private String doctor;
private List<String> questions;
public String getName() {
return name;
}
public String getDoctor() {
return doctor;
}
public List<String> getQuestions() {
return questions;
}
}
I want to parse json from json object and put it on textview. I tried some method but failed. The error:
expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
API SERVICE: Full ver http://139.255.86.189:83/service/api/checklistpertanyaan/1
{
"success": true,
"data": [
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
},
Harian.java
public class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
MainActivity.java
public class HarianActivity extends AppCompatActivity {
private TextView textViewResult;
/*private static String url = "http://139.255.86.189:83/service/api/checklistpertanyaan/1";*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harian);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.255.86.189:83/service/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HarianApi harianApi = retrofit.create(HarianApi.class);
Call<List<Harian>> call = harianApi.getHarian();
call.enqueue(new Callback<List<Harian>>() {
#Override
public void onResponse(Call<List<Harian>> call, Response<List<Harian>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("CodeL " + response.code());
return;
}
List<Harian> harians = response.body();
for (Harian harian : harians) {
String content = "";
content += "ID " + harian.getIdRchecklistpompa() + "\n";
content += "NAMA " + harian.getNmChecklist() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Harian>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
I would expect JSON that encapsulated a List of Harians to look like this:
[
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
}
]
Instead, yours begins with:
{
"success": true,
"data": [
...
So it isn't correct for your API to return List<Harian>. Instead, your API should return a different class which looks more like:
public class Container {
#SerializedName("success")
private boolean success;
#SerializedName("data")
List<Harian> data;
public static class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
}
And have your Retrofit API return Container rather than List<Harian>
Not sure if I understand but, to debug the problem what I would do is:
1.- Check as a String that response is a well formed JSON String.
Log.d(TAG, "My JSON String: " + response.code());
1.5.- Check if that string is a JSONObject or a JSONArray
2.- Probably try to create a JSONObject/JSONArray from that String to see if it triggers an exception.
try {
JSONObject jsonObject = new JSONObject(response.code());
} catch (JSONException e) {
e.printStackTrace();
}
3.- Try to parse the JSONObject but checking for exceptions:
try {
String nmChecklist = jsonObject.getString("nmChecklist");
} catch (JSONException e) {
e.printStackTrace();
}
4.- If you want to avoid exceptions since some objects may or may not have a key or value:
String nmChecklist = jsonObject.has("nmChecklist") && !jsonObject.isNull("nmChecklist") ? jsonObject.getString("nmChecklist") : null;
I hope this helps.
I think there is some problem with your class. The response is different from your pojo class. See json to pojo and create your Model as per the generated pojo.
I have my Android Java REST API code working perfectly with another REST API that uses a JSON object hierarchy (aka List-bracket-object1-bracket object2). Now I moved on to a simplified API (googlemaps timezone - just one simple object with 5 fields) but I cannot figure out how to get the google data into my object.
I am getting status code 200, I can see the googlemaps output/JSON in my logcat but my object is null. I read this post "0 Retrofit 2: response.body() is null, but status code is 200 2" and I am sure I have the same problem but I do not know how to adjust my object model to fix it. Here is my stuff...
1 - API/URL I am hitting:
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=xxxxxx
2 - What the API/URL returns (from my LogCat)
D/OkHttp: {
D/OkHttp: "dstOffset" : 0,
D/OkHttp: "rawOffset" : -28800,
D/OkHttp: "status" : "OK",
D/OkHttp: "timeZoneId" : "America/Los_Angeles",
D/OkHttp: "timeZoneName" : "Pacific Standard Time"
D/OkHttp: }
3 - Logcat showing object is null
Log.e(" main ", " apt " + response.body().getResults());
E/ main: apt null
4 - The calling routine
ApiInterface apiService = ApiClient.getClient(1).create(ApiInterface.class);
Call<ApiTimes> call = apiService.getTime(location,epoch,GOOG_TZ_KEY);
call.enqueue(new Callback<ApiTimes>() {
#Override
public void onResponse(Call<ApiTimes> call, Response<ApiTimes> response) {
int statusCode = response.code();
Log.e(" main ", " apt " + response.body().getResults());
}
#Override
public void onFailure(Call<ApiTimes> call, Throwable t) {
Log.e(" getFS ", t.toString());
}
});
5 - The object.
public class ApiTime {
#SerializedName("apitime")
private ApiTime apitime;
#SerializedName("dstOffset")
#Expose
private Long dstOffset;
#SerializedName("rawOffset")
#Expose
private Long rawOffset;
#SerializedName("status")
#Expose
private String status;
#SerializedName("timeZoneId")
#Expose
private String timeZoneId;
#SerializedName("timeZoneName")
#Expose
private String timeZoneName;
public ApiTime(Long dstOffset, Long rawOffset, String status, String timeZoneId, String timeZoneName) {
this.dstOffset = dstOffset ;
this.rawOffset = rawOffset ;
this.status = status ;
this.timeZoneId = timeZoneId ;
this.timeZoneName = timeZoneName ;
}
public ApiTime getResults() {
return apitime;
}
public void setResults(ApiTime apitimes) {
this.apitime = apitime;
}
public Long getDstOffset() {
return dstOffset;
}
public void setDstOffset(Long dstOffset) {
this.dstOffset = dstOffset;
}
public Long getRawOffset() {
return rawOffset;
}
public void setRawOffset(Long rawOffset) {
this.rawOffset = rawOffset;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeZoneId() {
return timeZoneId;
}
public void setTimeZoneId(String timeZoneId) {
this.timeZoneId = timeZoneId;
}
public String getTimeZoneName() {
return timeZoneName;
}
public void setTimeZoneName(String timeZoneName) {
this.timeZoneName = timeZoneName;
}
#Override
public String toString() {
return "ApiTime{" +
"dstOffset=" + dstOffset +
", rawOffset=" + rawOffset +
", status='" + status + '\'' +
", timeZoneId='" + timeZoneId + '\'' +
", timeZoneName='" + timeZoneName + '\'' +
'}';
}
}
6 - Here are the two invocation routines:
public class ApiClient {
public static final String URL0 = blah blah
public static final String URL1 = "https://maps.googleapis.com/maps/api/timezone/";
private static Retrofit retrofit = null;
public static String BASE_URL = "www.google.com";
public static Retrofit getClient(int url) {
BASE_URL = URL0;
if (url == 1){
BASE_URL = URL1;
}
//The following block of code generates OkHttpClient loggging to LogCat.
//Only use if debugging.
OkHttpClient.Builder client = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(loggingInterceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
//Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(BASE_URL)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
return retrofit;
}
}
public interface ApiInterface {
#GET("json")
Call<ApiTimes> getTime(#Query("location") String location, #Query("timestamp") String timestamp, #Query("key") String key);
}
Looks like you should use ApiTime instead of ApiTimes
I don't see #SerializedName("apitimes") in your json in logs
public interface ApiInterface {
#GET("json")
Call<ApiTime> getTime(#Query("location") String location, #Query("timestamp") String timestamp, #Query("key") String key);
}
-
ApiInterface apiService = ApiClient.getClient(1).create(ApiInterface.class);
Call<ApiTime> call = apiService.getTime(location, epoch, GOOG_TZ_KEY);
call.enqueue(new Callback<ApiTime>() {
#Override
public void onResponse(Call<ApiTime> call, Response<ApiTime> response) {
int statusCode = response.code();
Log.e("main", "apt " + response.body());
}
#Override
public void onFailure(Call<ApiTime> call, Throwable t) {
Log.e("getFS ", t.toString());
}
});
-
public class ApiTime {
#SerializedName("dstOffset")
private Long dstOffset;
#SerializedName("rawOffset")
private Long rawOffset;
#SerializedName("status")
private String status;
#SerializedName("timeZoneId")
private String timeZoneId;
#SerializedName("timeZoneName")
private String timeZoneName;
// getters here
}
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'
}]
}
I am using Eclipse IDE to parse the Json data from URl but everty time i run this code it returns null values.
This is the json data from URL
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
This is the POJO class
package com.beto.test.json;
public class Data {
private String id;
private String body;
private String title;
private String userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public String toString() {
return "ClassPojo [id = " + id + ", body = " + body + ", title = " + title + ", userId = " + userId + "]";
}
}
JsonParserUrl.java class
package com.beto.test.json;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;
/**
* Created by BeytullahC on 23.03.2015.
*/
public class JsonParserFromUrl {
public static void main(String[] args) {
DefaultHttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
HttpResponse response = getResponse("http://jsonplaceholder.typicode.com/posts", httpClient);
String outPut = readData(response);
System.out.println(outPut);
Gson gson = new Gson();
List<Data> fromJson = gson.fromJson(outPut, new TypeToken<List<Data>>(){}.getType());
System.out.println("DATA SIZE : "+fromJson.size());
System.out.println("GET FIRST DATA : "+fromJson.get(0));
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
public static HttpResponse getResponse(String url, DefaultHttpClient httpClient) throws IOException {
try {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(httpGet);
return response;
} catch (IOException e) {
throw e;
}
}
public static String readData(HttpResponse response) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer data = new StringBuffer();
char[] dataLength = new char[1024];
int read;
while (((read = reader.read(dataLength)) != -1)) {
data.append(dataLength, 0, read);
}
return data.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
TestRunner.java class
package com.beto.test.json;
public class TestRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Data data = JsonParserfromUrl.getData("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("result:\n" +data);
}
catch(Exception e)
{
System.out.println("error");
}
}}
Liberaries Added :
- gson-2.3.1.jar
- httpclient-4.5.jar
- commons-logging-1.1.1.jar
- httpclient-cache-4.4.jar
- httpmime-4.0.jar
- commons-codec-1.1.jar
- httpcore-4.4.jar
OUTPUT
ClassPojo [id = " null ", body = " null ", title = " null ", userId ="null"]
Please solve this problem , it should not return null values.
First you should get the JSON String and then parse it to the Data class.
String yourJsonString = readUrl("http://jsonplaceholder.typicode.com/posts/1");
Gson gson = new Gson();
Data data = gson.fromJson(yourJsonString, Data.class);