I am trying to post a request via a JSON body through Retrofit2 in Android.
I am trying to hit api at https://magicspree.com/restaurant/webservice/android/login.
Here is my code.`
Input json body (requests via POST method):
{
"restaurantapikey":"v4Vk2wEkzZfWGxeChavYKLnamLrXaDUJTpiInqeU",
"restaurantusername":"dvar.rddwarka.del",
"restaurantpassword":"password"
}
Restaurant.java(model class):
public class Restaurant {
#SerializedName("restaurantApiKey")
private String restaurantApiKey;
#SerializedName("restaurantUserName")
private String restaurantUserName;
#SerializedName("restaurantPassword")
private String restaurantPassword;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("Text")
#Expose
private String text;
#SerializedName("Restaurant_id")
#Expose
private Integer restaurantId;
public String getRestaurantApiKey() {
return restaurantApiKey;
}
public void setRestaurantApiKey(String restaurantApiKey) {
this.restaurantApiKey = restaurantApiKey;
}
public String getRestaurantUserName() {
return restaurantUserName;
}
public void setRestaurantUserName(String restaurantUserName) {
this.restaurantUserName = restaurantUserName;
}
public String getRestaurantPassword() {
return restaurantPassword;
}
public void setRestaurantPassword(String restaurantPassword) {
this.restaurantPassword = restaurantPassword;
}
public Restaurant(String apiKey, String userName,String password) {
this.restaurantApiKey = apiKey;
this.restaurantUserName = userName;
this.restaurantPassword=password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Integer restaurantId) {
this.restaurantId = restaurantId;
}
public String toString(){
return "id="+restaurantId+", status="+getStatus()+", text="+getText();
}
}
ApiClient.java:
public class ApiClient {
public static final String BASE_URL =
"https://magicspree.com/restaurant/webservice/android/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface.java:
public interface ApiInterface {
#POST("login")
Call<Restaurant> loginRestaurant(#Body Restaurant restaurant);
}
My onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Restaurant r=new Restaurant("v4Vk2wEkzZfWGxeChavYKLnamLrXaDUJTpiInqeU","dvar.rddwarka.del","password");
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Restaurant> call = apiService.loginRestaurant(r);
call.enqueue(new Callback<Restaurant>() {
#Override
public void onResponse(Call<Restaurant> call2, Response<Restaurant> response) {
System.out.println(response.body().toString());
}
#Override
public void onFailure(Call<Restaurant> call, Throwable t) {
}
});
}
Expected output JSON:
{"Status":"Success","Text":"Login Successful","Restaurant_id":27}
The problem is that I am getting the values as Status:Failed, Text:Null, and Restaurant_id:0. I have just started with Retrofit so I do not understand it properly. Please tell me how to retrieve the expected values correctly.
This can be naive but with my eagle eyes :) I see that in Postman your parameter is all in lower case while in your code it is Camel case (restaurantapikey
vs restaurantApiKey )
It might be your backend is implemented with case sensitive parameter.
Change your Restaurant class to use this :
#SerializedName("restaurantapikey")
private String restaurantApiKey;
#SerializedName("restaurantusername")
private String restaurantUserName;
#SerializedName("restaurantpassword")
private String restaurantPassword;
Related
I have an issue with Json
when i use Gson everything is working properly, but when i use retrofit2 something is going wrong.
Class structure is exact same between retrofit and gson. difference is one additional interface and retrofit codes which is working in different cases
i uploaded every piece of code here.
String json2 = "{\"busList\":{\"bus\":[{\"forward\":\"true\",\"lat\": \"41.718979\",\"lon\": \"44.770645\",\"nextStopId\": \"1858\",\"routeNumber\": \"42\"},{\"forward\": \"true\",\"lat\": \"41.71735\",\"lon\": \"44.777855\",\"nextStopId\": \"924\",\"routeNumber\": \"42\" }]}}";
//project structure
//Class1
public class FatherBusList {
#SerializedName("busList")
private BusList busList;
public FatherBusList(BusList busList){
this.busList = busList;
}
public BusList getBusList() {
return busList;
}
}
//Class2
public class BusList {
#SerializedName("bus")
private List<Bus> buses;
public BusList (List<Bus> busses){
this.buses = busses;
}
public List<Bus> getBuses() {
return buses;
}
}
//Class3
public class Bus {
private String forward;
private String lat;
private String lon;
private String nextStopId;
private String routeNumber;
public Bus(String forward, String lat, String lon, String nextStopId, String routeNumber) {
this.forward = forward;
this.lat = lat;
this.lon = lon;
this.nextStopId = nextStopId;
this.routeNumber = routeNumber;
}
public String getForward() {
return forward;
}
public String getLat() {
return lat;
}
public String getLon() {
return lon;
}
public String getNextStopId() {
return nextStopId;
}
public String getRouteNumber() {
return routeNumber;
}
}
//retrofit2 code
//Interface for request
public interface TtcApi {
#GET("buses?routeNumber=37&forward=1&_dc=1556996108032")
Call<FatherBusList> getBus();
}
//MainActivivty
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://transit.ttc.com.ge/pts-portal-services/")
.addConverterFactory(GsonConverterFactory.create())
.build();
TtcApi ttcApi = retrofit.create(TtcApi.class);
Call<FatherBusList> call = ttcApi.getBus();
call.enqueue(new Callback<FatherBusList>() {
#Override
public void onResponse(Call<FatherBusList> call, Response<FatherBusList> response) {
if (!response.isSuccessful()) {
textView.setText("Code: " + response.code());
return;
}
Toast.makeText(MainActivity.this, "Successful", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FatherBusList> call, Throwable t) {
textView.setText(t.getMessage());
}
});
}
}
I expect to busList have 1 object and this object have arrayList
But its output is null.
{
"bus": [
{
"forward": "true",
"lat": "41.690926",
"lon": "44.816879",
"nextStopId": "1012",
"routeNumber": "37"
}
]
}
I request for your interface, return it.
Your need direct use 'BusList' class entity,don't use 'FatherBusList'
I'm trying to use New York Times API with Retrofit using Observable. But I'm getting this error when trying to use datas.
Can someone help me see where I'm wrong, please ?
Here is my ApiServices interface:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<TopStoryResult> getTopStories();
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Here is my ApiStreams class
public static Observable<TopStoryResult> streamFetchTopStories(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getTopStories()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
public static Observable<List<NewsItem>> streamFetchNews(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getResults()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
And this is what I'm trying to do in my MainActivity. For now I just want to display in a TextView the list of each Title...
//------------------------
// Update UI
//------------------------
private void updateUIWhenStartingHttpRequest() {
this.textView.setText("Downloading...");
}
private void updateUIWhenStopingHttpRequest(String response) {
this.textView.setText(response);
}
//------------------------
// Rx Java
//------------------------
private void executeRequestWithRetrofit(){
this.updateUIWhenStartingHttpRequest();
this.disposable = ApiStreams.streamFetchNews()
.subscribeWith(new DisposableObserver<List<NewsItem>>(){
#Override
public void onNext(List<NewsItem> topStories) {
Log.e("TAG", "On Next");
updateUIWithResult(topStories);
}
#Override
public void onError(Throwable e) {
Log.e("ERROR", Log.getStackTraceString(e));
}
#Override
public void onComplete() {
Log.e("TAG", "On Complete !");
}
});
}
private void updateUIWithResult(List<NewsItem> newsItemList){
StringBuilder mStringBuilder = new StringBuilder();
for (NewsItem news : newsItemList){
Log.e("TAG", "UPDATE UI" + news.getTitle());
mStringBuilder.append("- " + news.getTitle() + "\n");
}
updateUIWhenStopingHttpRequest(mStringBuilder.toString());
}
[EDIT]
There are my two models for TopStories and NewsItem
TopStories:
private String status;
private String copyright;
private String section;
private String lastUpdated;
private Integer numResults;
private List<NewsItem> results = null;
public String getStatus() {return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Integer getNumResults() {
return numResults;
}
public void setNumResults(Integer numResults) {
this.numResults = numResults;
}
public List<NewsItem> getResults() {
return results;
}
public void setResults(List<NewsItem> results) {
this.results = results;
}
NewsItem:
private String section;
private String subsection;
private String title;
private String url;
private String byline;
private String updated_date;
private String created_date;
private String published_date;
private String material_type_facet;
private String kicker;
#SerializedName("abstract")
private String abstract_string;
private List<Multimedia> multimedia;
private transient String des_facet;
private transient String org_facet;
private transient String per_facet;
private transient String geo_facet;
public NewsItem() {
}
public NewsItem(String url) {
this.url = url;
}
public NewsItem(String section, String subsection, String title, String url, String byline, String updated_date, String created_date, String published_date, String material_type_facet, String kicker) {
this.section = section;
this.subsection = subsection;
this.title = title;
this.url = url;
this.byline = byline;
this.updated_date = updated_date;
this.created_date = created_date;
this.published_date = published_date;
this.material_type_facet = material_type_facet;
this.kicker = kicker;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSubsection() {
return subsection;
}
public void setSubsection(String subsection) {
this.subsection = subsection;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getByline() {
return byline;
}
public void setByline(String byline) {
this.byline = byline;
}
public String getUpdated_date() {
return updated_date;
}
public void setUpdated_date(String updated_date) {
this.updated_date = updated_date;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getPublished_date() {
return published_date;
}
public void setPublished_date(String published_date) {
this.published_date = published_date;
}
public String getMaterial_type_facet() {
return material_type_facet;
}
public void setMaterial_type_facet(String material_type_facet) {
this.material_type_facet = material_type_facet;
}
public String getKicker() {
return kicker;
}
public void setKicker(String kicker) {
this.kicker = kicker;
}
public String getAbstract() {
return abstract_string;
}
public void setAbstract(String abstract_string) {
this.abstract_string = abstract_string;
}
public List<Multimedia> getMultimedia() {
return multimedia;
}
public void setMultimedia(List<Multimedia> multimedia) {
this.multimedia = multimedia;
}
public String getDes_facet() {
return des_facet;
}
public void setDes_facet(String des_facet) {
this.des_facet = des_facet;
}
public String getOrg_facet() {
return org_facet;
}
public void setOrg_facet(String org_facet) {
this.org_facet = org_facet;
}
public String getPer_facet() {
return per_facet;
}
public void setPer_facet(String per_facet) {
this.per_facet = per_facet;
}
public String getGeo_facet() {
return geo_facet;
}
public void setGeo_facet(String geo_facet) {
this.geo_facet = geo_facet;
}
Here is what the JSON looks like:
JSON
First when I tried this one with Github user API, it works fine. But I can't figure out where I'm wrong there...
Is anybody can help me please ?
Thanks a lot !
Expected BEGIN_ARRAY but was BEGIN_OBJECT
this means you are trying to a get a JSON Array as a List in JAVA but the api sent you a JSON OBJECT. So I cannot gather enough information but if I have to guess you should change this
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
to
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<NewsItemObject> getResults();
NewsItemObject is the Class that wraps NewsItem
In your ApiServices interface you expect that getResults() returns Observable<List<NewsItem>>. Based on JSON you getting back this is not gonna work, because your root JSON element is Object, not an Array.
You have to create new wrapper Class (ResultsWrapper) with "results" field type of List<NewsItem>. Your method in ApiServices interface will then be:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<ResultsWrapper> getResults();
That is what "Expected BEGIN_ARRAY but was BEGIN_OBJECT" says to you.
hi guys i have a api like this you can see i have a metaData array and all of the items in the array have a Integer id and a string key but value is not the same in all of them i defined the value in the Object but i have an error this is the error
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3871 path $[0].meta_data
and this is my POJO class
Main Pojo(Product) class
#SerializedName("meta_data")
#Expose
private MetaDatum metaData;
and this is the MetaDatum Class
public class MetaDatum implements Parcelable {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("key")
#Expose
private String key;
#SerializedName("value")
#Expose
private Object value;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.key);
dest.writeParcelable((Parcelable) this.value, flags);
}
public MetaDatum() {
}
protected MetaDatum(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.key = in.readString();
this.value = in.readParcelable(Object.class.getClassLoader());
}
public static final Parcelable.Creator<MetaDatum> CREATOR = new Parcelable.Creator<MetaDatum>() {
#Override
public MetaDatum createFromParcel(Parcel source) {
return new MetaDatum(source);
}
#Override
public MetaDatum[] newArray(int size) {
return new MetaDatum[size];
}
};
}
make all pojo class for your json data using robopojo puligns or http://www.jsonschema2pojo.org/
after that make retrofit object define base url and other things...
public class ApiClient {
private final static String BASE_URL = "https://goorab.com/wp-json/wc/v2/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
and make interface for api calling..
public interface ApiInterface {
#GET("products")
Call<ResponseData> getdata(#Query("consumer_key") String key);
}
after that calling into activity or fragment like below.
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<ResponseData> responseCall = apiInterface.getdata("pass key");
responseCall.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
if (response.isSuccessful() && response.body() != null && response != null) {
Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
Log.d("Errror", t.getMessage());
}
});
and make sure pojo class are all valid.
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)
Your meta_data is array instead of object
meta_data": [
{
"id": 3281,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
]
So use List
private List<MetaDatum> metaData;
I want to get data from the server (https://data.egov.kz/api/v2/zheke_zhane_zandy_tulgalardy_k1/v6?pretty) as an array of json objects. But I get this Log:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I am using Retrofit2 and here my code:
MainActivity.java
public class MainActivity extends AppCompatActivity
implements GetAdmissionSchedule.GetAdmissionScheduleInterface {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetAdmissionSchedule getAdmissionSchedule = new GetAdmissionSchedule(this);
getAdmissionSchedule.getAdmissionScheduleList();
}
#Override
public void getAdmissionSchedule(List<AdmissionSchedule> admissionScheduleList) {
// here i get my data
}
}
GetAdmissionSchedule.java
public class GetAdmissionSchedule {
private GetAdmissionScheduleInterface getAdmissionScheduleInterface;
public GetAdmissionSchedule(GetAdmissionScheduleInterface getAdmissionScheduleInterface) {
this.getAdmissionScheduleInterface = getAdmissionScheduleInterface;
}
public interface GetAdmissionScheduleInterface {
void getAdmissionSchedule(List<AdmissionSchedule> admissionScheduleList);
}
public void getAdmissionScheduleList() {
DataEgovApi service = DataEgovBaseURL.getRetrofit();
Call<List<AdmissionSchedule>> call = service.getAdmissionScheduleList();
call.enqueue(new Callback<List<AdmissionSchedule>>() {
#Override
public void onResponse(Call<List<AdmissionSchedule>> call, Response<List<AdmissionSchedule>> response) {
Log.d("MyLogs", "MVD: getAdmissionScheduleList " + response.code());
getAdmissionScheduleInterface.getAdmissionSchedule(response.body());
}
#Override
public void onFailure(Call<List<AdmissionSchedule>> call, Throwable t) {
Log.d("MyLogs", "MVD: getAdmissionScheduleList " + t.getLocalizedMessage());
getAdmissionScheduleInterface.getAdmissionSchedule(null);
}
});
}
}
DataEgovBaseURL.java
public class DataEgovBaseURL {
private static final String BASE_URL = "https://data.egov.kz/";
private static Retrofit retrofit = null;
public static DataEgovApi getRetrofit() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit.create(DataEgovApi.class);
}
}
DataEgovApi.java
public interface DataEgovApi {
#GET("api/v2/zheke_zhane_zandy_tulgalardy_k1/v6?pretty")
Call<List<AdmissionSchedule>> getAdmissionScheduleList();
}
AdmissionSchedule.java (My POJO class)
public class AdmissionSchedule {
#SerializedName("id")
#Expose
private String id;
#SerializedName("vremia")
#Expose
private String vremia;
#SerializedName("adres_ru")
#Expose
private String adresRu;
#SerializedName("doljnost_ru")
#Expose
private String doljnostRu;
#SerializedName("name_ru")
#Expose
private String nameRu;
#SerializedName("data")
#Expose
private String data;
#SerializedName("adres_kz")
#Expose
private String adresKz;
#SerializedName("doljnost_kz")
#Expose
private String doljnostKz;
#SerializedName("name_kz")
#Expose
private String nameKz;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVremia() {
return vremia;
}
public void setVremia(String vremia) {
this.vremia = vremia;
}
public String getAdresRu() {
return adresRu;
}
public void setAdresRu(String adresRu) {
this.adresRu = adresRu;
}
public String getDoljnostRu() {
return doljnostRu;
}
public void setDoljnostRu(String doljnostRu) {
this.doljnostRu = doljnostRu;
}
public String getNameRu() {
return nameRu;
}
public void setNameRu(String nameRu) {
this.nameRu = nameRu;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAdresKz() {
return adresKz;
}
public void setAdresKz(String adresKz) {
this.adresKz = adresKz;
}
public String getDoljnostKz() {
return doljnostKz;
}
public void setDoljnostKz(String doljnostKz) {
this.doljnostKz = doljnostKz;
}
public String getNameKz() {
return nameKz;
}
public void setNameKz(String nameKz) {
this.nameKz = nameKz;
}
}
You server url is https and certificate is already not valid.
Change https to http and it will work.
Else you can install valid SSL certificate on the server.
I have tried several ways to create follwing format json using java. (Gson , Jackson , ...)
{
"outbound": {
"address": [
"t91",
"t0992"
],
"send": "t678",
"outMessage": {
"message": "Hello World"
},
"client": "156",
"receipt": {
"URL": "http://example.com/Delivery",
"callback": "some-to-the-request"
},
"senderName": "Inc."
}
}
Any help?
Use code below.
Create POJO
public class TestPojo {
private Outbound outbound;
public Outbound getOutbound() {
return outbound;
}
public void setOutbound(Outbound outbound) {
this.outbound = outbound;
}
}
class Outbound {
private String[] address;
private String send;
private OutMessage outMessage;
private Receipt receipt;
private String senderName;
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public OutMessage getOutMessage() {
return outMessage;
}
public void setOutMessage(OutMessage outMessage) {
this.outMessage = outMessage;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
}
class OutMessage {
private String message;
public OutMessage(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Receipt {
private String URL;
private String callback;
public Receipt(String uRL, String callback) {
super();
URL = uRL;
this.callback = callback;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
Main Class (JSON to Object)
String json = "{'outbound':{'address':['t91','t0992'],'send':'t678','outMessage':{'message':'Hello World'},'receipt':{'URL':'http://example.com/Delivery','callback':'some-to-the-request'},'senderName':'Inc.'}}";
TestPojo testPojo = new Gson().fromJson(json, TestPojo.class);
System.out.println(testPojo.getOutbound().getSenderName());
Output
Inc.
Main Class (Object to JSON)
TestPojo testPojo = new TestPojo();
Outbound outbound = new Outbound();
outbound.setAddress(new String[]{"t91", "t0992"});
outbound.setOutMessage(new OutMessage("Hello World"));
outbound.setReceipt(new Receipt("http://example.com/Delivery", "some-to-the-request"));
outbound.setSenderName("Inc.");
outbound.setSend("t678");
testPojo.setOutbound(outbound);
System.out.println(new Gson().toJson(testPojo));
Output
{"outbound":{"address":["t91","t0992"],"send":"t678","outMessage":{"message":"Hello World"},"receipt":{"URL":"http://example.com/Delivery","callback":"some-to-the-request"},"senderName":"Inc."}}
Detail
Used GSON library.
Used a json given by you.