Get data from json using Retrofit [duplicate] - java

This question already has answers here:
How to get List<String> from JSON list using Retrofit 2?
(2 answers)
Closed 2 years ago.
I'm trying to get some data from JSON below using Retrofit:
[
{
"country": "China",
"cases": 80650,
"todayCases": 98,
"deaths": 3070,
"todayDeaths": 28,
"recovered": 55402,
"critical": 5737
},
{
"country": "S. Korea",
"cases": 6593,
"todayCases": 309,
"deaths": 43,
"todayDeaths": 1,
"recovered": 135,
"critical": 52
}
....
]
I've tried the below code without success :
Interface :
public interface CoronaInterface {
#GET("all")
public Call<Resume> getCoronaVirusResumeInformation();
#GET("countries")
public Call<Complete> getCoronaVirusCompleteInformation();
}
Models
public class Data {
#SerializedName("country")
private String country;
#SerializedName("recovered")
private String recovered;
#SerializedName("cases")
private String cases;
#SerializedName("critical")
private String critical;
#SerializedName("deaths")
private String deaths;
#SerializedName("todayCases")
private String todayCases;
#SerializedName("todayDeaths")
private String todayDeaths;
public String getCountry() {
return country;
}
public String getRecovered() {
return recovered;
}
public String getCases() {
return cases;
}
public String getCritical() {
return critical;
}
public String getDeaths() {
return deaths;
}
public String getTodayCases() {
return todayCases;
}
public String getTodayDeaths() {
return todayDeaths;
}
}
public class Complete {
private Data[] mData;
public Data[] getData() {
return mData;
}
public void setData(Data[] mData) {
this.mData = mData;
}
}
MainActivity :
mCallComplete = mCoronaInterface.getCoronaVirusCompleteInformation();
mCallComplete.enqueue(new Callback<Complete>() {
#Override
public void onResponse(#NonNull Call<Complete> call, #NonNull Response<Complete> response) {
}
#Override
public void onFailure(#NonNull Call<Complete> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "ops", Toast.LENGTH_SHORT).show();
}
});
My issue: I always get ops message at runtime.

Show Retrofit object. Did you test your api using for example Postman program? is it working?

Replace "ops" with t.toString() to see the details of what caused the error. As mentioned, you need to provide source of the API.

Related

Android Retrofit - Putting the response into an arraylist

Hey guys I have retrofit successfully getting data from a rest API and its printing into the log. However when I try and capture this response into an array list I'm getting an error stating : "Cannot infer arguments (unable to resolve constructor). This error shows in the array list brackets <>
// Executes the network request on a background thread
try {
Response response = getWeather(locationCode, apiKey).execute();
if (cancelRequest) {
return;
}
if (response.code() == 200) {
// Weather weather = response.body().getWeather();
Log.d(TAG, "onResponse: " + response.body().toString());
List<Weather> list = new ArrayList<>(((Weather)response.body()));
//mWeather.postValue(response);
GSON Response
{
"coord": {
"lon": -5.93,
"lat": 54.58
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 291.56,
"feels_like": 286.36,
"temp_min": 291.15,
"temp_max": 292.15,
"pressure": 1024,
"humidity": 45
},
If anyone could help me root cause this it would be greatly appreciated.
I feel the POJO Class which you have created might not be proper as you have not shared your POJO class please try the below POJO class in your code an see if the error still persists.
public class Weather {
private coordinate coord;
private ArrayList<weatherinfo> weather;
private String base;
private maininfo main;
public coordinate getCoord() {
return coord;
}
public ArrayList<weatherinfo> getWeather() {
return weather;
}
public String getBase() {
return base;
}
public maininfo getMain() {
return main;
}
public static class coordinate{
String lon,lat;
public String getLon() {
return lon;
}
public String getLat() {
return lat;
}
}
public static class weatherinfo{
String id,main,description,icon;
public String getId() {
return id;
}
public String getMain() {
return main;
}
public String getDescription() {
return description;
}
public String getIcon() {
return icon;
}
}
public static class maininfo{
String temp,feels_like,temp_min,temp_max,pressure,humidity;
public String getTemp() {
return temp;
}
public String getFeels_like() {
return feels_like;
}
public String getTemp_min() {
return temp_min;
}
public String getTemp_max() {
return temp_max;
}
public String getPressure() {
return pressure;
}
public String getHumidity() {
return humidity;
}
}
}
After that while reading your response try it this way.
ArrayList<Weather.weatherinfo> list = response.body().getWeather();
Happy Coding
To convert the response to a usable java object, you will have to use Gson or use Retrofit to do it automatically. Since you are getting the generic Response from the call, it means you will have to do it yourself. So first convert the json schema to a POJO then instead of
List<Weather> list = new ArrayList<>(((Weather)response.body()));
use
ResponsePojo responsePojo = gson.fromJson(response.body().toString(), ResponsePojo.class);
However, instead of doing it manually, you should set up Retrofit correctly so that it does the conversion for you. Then you will get back your object directly from the retrofit call -
Response<ResponsePojo> response = getWeather(locationCode, apiKey).execute();
ResponsePojo responsePojo = response.body()

Retrofit not parsing in Android

I am having trouble parsing the values and displaying in the recyclerview made the Pojo class's in jsonschema2pojo, but when i run the app, it shows the toast in the enqueue OnFailure(), i tried multiple things but no success any help i think it can be about the expecting jsonArray/jsonObject thing ?
Thank you in advance.
I want to get the values inside the array results[]
Json response given below:
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
APIReponse pojo class:
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
MetaData pojo class:
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
Result pojo class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
This is retrofit API interface:
#GET("search/phone/page/1/")
Call<List<Result>> getAllPhones();
Retrofit call methods:
Call<List<Result>> call = service.getAllPhones();
call.enqueue(new Callback<List<Result>>() {
#Override
public void onResponse(Call<List<Result>> call, Response<List<Result>> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<List<Result>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
You have to use your APIResponse Class as Result from your call
#GET("search/phone/page/1/")
Call<APIResponse> getAllPhones();
and you have to change your onResponse Method:
call.enqueue(new Callback<APIResponse>() {
#Override
public void onResponse(Call<APIResponse> call, Response<APIResponse> response) {
generatePhonesList(response.body().metadata.results);
}
#Override
public void onFailure(Call<APIResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
You need create data class same:
class DataResponse {
val success: String = ""
val metadata: MetadataResponse? = null
class MetadataResponse {
val sort: String = ""
val total_products: Int = 0
val title: String = ""
val results: List<ItemResult> = arrayListOf()
class ItemResult {
val sku: String = ""
val name: String = ""
val brand: String = ""
val max_saving_percentage: Int = 0
val price: Int = 0
val special_price: Int = 0
val image: String = ""
val rating_average: Int = 0
}
}
And:
#GET("search/phone/page/1/")
Call<DataResponse> getAllPhones();
And:
Call<DataResponse> call = service.getAllPhones();
call.enqueue(new Callback<DataResponse>() {
#Override
public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
val itemResults = response.metadata?.results
}
#Override
public void onFailure(Call<List<Result>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
You should use APIReponse instead of Result class
Like this.
#GET("search/phone/page/1/")
Call<APIReponse> getAllPhones();

Cannot deserialize instance of `org.json.JSONObject`

I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.
In 1 of the controller this is the body I send:
{
"depositHotel": "xxx",
"destinationHotel": "aaa",
"depositHotelAmount": "0.2",
"destinationHotelAmount": "4",
"destinationAddress": [{
"address": "asdf",
"tag": ""
}],
"refundAddress": [{
"address": "pio",
"tag": ""
}]
}
so I create this class to use it as a RequestBody:
public class HotelswitchHotelOrderRequestBody {
public static class Builder {
private String depositHotel;
private String destinationHotel;
private Float depositHotelAmount;
private Float destinationHotelAmount;
private JSONObject destinationAddress;
private JSONObject refundAddress;
public Builder(String depositHotel, String destinationHotel) {
this.depositHotel = depositHotel;
this.destinationHotel = destinationHotel;
}
public Builder withDepositHotelAmount (Float depositHotelAmount) {
this.depositHotelAmount = depositHotelAmount;
return this;
}
public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
this.destinationHotelAmount = destinationHotelAmount;
return this;
}
public Builder toDestinationAddress (JSONObject destinationAddress) {
this.destinationAddress = destinationAddress;
return this;
}
public Builder toRefundAddress (JSONObject refundAddress) {
this.refundAddress = refundAddress;
return this;
}
public HotelswitchHotelOrderRequestBody build(){
HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
order.depositHotel = this.depositHotel;
order.depositHotelAmount = this.depositHotelAmount;
order.destinationAddress = this.destinationAddress;
order.destinationHotel = this.destinationHotel;
order.destinationHotelAmount = this.destinationHotelAmount;
order.refundAddress = this.refundAddress;
return order;
}
}
private String depositHotel;
private String destinationHotel;
private Float depositHotelAmount;
private Float destinationHotelAmount;
private JSONObject destinationAddress;
private JSONObject refundAddress;
private HotelswitchHotelOrderRequestBody () {
//Constructor is now private.
}
public String getDepositHotel() {
return depositHotel;
}
public void setDepositHotel(String depositHotel) {
this.depositHotel = depositHotel;
}
public String getDestinationHotel() {
return destinationHotel;
}
public void setDestinationHotel(String destinationHotel) {
this.destinationHotel = destinationHotel;
}
public Float getDepositHotelAmount() {
return depositHotelAmount;
}
public void setDepositHotelAmount(Float depositHotelAmount) {
this.depositHotelAmount = depositHotelAmount;
}
public Float getDestinationHotelAmount() {
return destinationHotelAmount;
}
public void setDestinationHotelAmount(Float destinationHotelAmount) {
this.destinationHotelAmount = destinationHotelAmount;
}
public JSONObject getDestinationAddress() {
return destinationAddress;
}
public void setDestinationAddress(JSONObject destinationAddress) {
this.destinationAddress = destinationAddress;
}
public JSONObject getRefundAddress() {
return refundAddress;
}
public void setRefundAddress(JSONObject refundAddress) {
this.refundAddress = refundAddress;
}
}
But I have this error when receiving the object:
JSON parse error: out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token
JSONObject's representation in actual JSON is a hash i.e. {...}. In your json data you're providing an array of hashes [{...}] which is not the same. Judging from your domain I don't think it has to be multiple values, so you can just omit [] in your payload and if it does then the fields in your Java class can be defined as JSONArray.
However, I think you should go with defining an Address class and either using
private Address destinationAddress;
private Address refundAddress;
or if it indeed does have to be an object array
private List<Address> destinationAddresses;
private List<Address> refundAddresses;
I had a similar usecase , where I could not define the json to a POJO. Using com.fasterxml.jackson.databind.JsonNode instead of the JSONObject worked.

How to get data from retrofit when data is like this as given below

When I try to get name while parsing the response from the server, I am getting null. Can u please help me to get data i.e, name, email and keyskills.name?
The JSON response is here.
{
"freelancer": {
"id": 3,
"name": "trinadh",
"title": "web developer",
"email": "trinadh_freelancer#gmail.com",
"gender": "Male",
"dob": "2018-09-27",
"website": "www.trinadh_freelancer.com",
"country": "India",
"state": "Karnataka",
"city": "Bangalore",
"user_id": 52,
"user_role": "freelancer",
"registered": null,
"agreement": true,
"address": "hsr layout",
"qualification": "b.tech",
"total_experience": "2",
"prefered_location": "",
"category": "Web Development",
"pancard_number": "ajhfvbqjhe",
"passport_number": "hbhfjdhbjfh",
"country_code": null,
"contact_number": "8765456721",
"currency_type": "INR",
"rate": "678.0",
"rate_card_type": "per_hour",
"negotiable": true,
"taxes": "Taxes Excluded",
"key_skills": {
"name": "ruby",
"relevant_experience": "2"
},
"other_skills": {
"name": "animation",
"relevant_experience": "3"
},
"confirmed_at": "24-Sep-2018",
"free_trail_days_left": 83,
"renewal_date": "24-Mar-2019",
"image": "<img src=\"\" />"
}
}
Here is my pojo class
public class FreeLancer {
private List<FreeLancerProfile> freelancer;
// Constructors, getters and setters are removed for convenience
}
Here is my freelancer profile
public class FreeLancerProfile {
private int id;
private String name;
private String title;
private String email;
private String gender;
private String dob;
private String website;
private String country;
private String state;
private String city;
private int user_id;
private String user_role;
private String registered;
private String agreement;
private String address;
private String qualification;
private String total_experience;
private String prefered_location;
private String category;
private String pancard_number;
private String passport_number;
private String country_code;
private String contact_number;
private String currency_type;
private String rate;
private String rate_card_type;
private String negotiable;
private String taxes;
private List<KeySkill> key_skills;
private List<OtherSkill> other_skills;
private String confirmed_at;
private String free_trail_days_left;
private String renewal_date;
private String image;
// Constructors, getters and setters are removed for convenience
}
My Pojo class for key skills
public class KeySkill {
private int id;
private String name;
private String relevant_experience;
// Constructors, getters and setters are removed for convenience
}
My Interface
public interface FreeLancerMainApi {
#GET("{fullUrl}/profile")
Call<FreeLancerProfile> freeLancerMain(
#Path(value = "fullUrl", encoded = true) String fullUrl,
#Header("Authorization") String token
);
#GET("{fullUrl}/profile")
Call<KeySkill> keySkillsMain(
#Path(value = "fullUrl", encoded = true) String fullUrl,
#Header("Authorization") String token
);
}
My Main Avtivity
String BASE_URL = "http://74.207.233.160/api/v1/freelancers/";
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
final FreeLancerMainApi api = retrofit.create(FreeLancerMainApi.class);
Call<FreeLancerProfile> call = api.freeLancerMain(freelancer_id, token);
call.enqueue(new Callback<FreeLancerProfile>() {
#Override
public void onResponse(Call<FreeLancerProfile> call, Response<FreeLancerProfile> response) {
if (response.code() == 200)
{
name = response.body().getName();
email = response.body().getEmail();
contactNumber = response.body().getContact_number();
Toast.makeText(FreelancerActivity.this, name, Toast.LENGTH_SHORT).show();
}
else {
}
}
#Override
public void onFailure(Call<FreeLancerProfile> call, Throwable t) {
}
});
Call<KeySkill> call1 = api.keySkillsMain(freelancer_id, token);
call1.enqueue(new Callback<KeySkill>() {
#Override
public void onResponse(Call<KeySkill> call, Response<KeySkill> response) {
if (response.code() == 200){
skills = response.body().getName();
}else {
}
}
#Override
public void onFailure(Call<KeySkill> call, Throwable t) {
}
});
freeLancerMainName.setText(name);
freeLancerMainEmail.setText(email);
freeLancerContactNumber.setText(contactNumber);
freeLancerKeySkills.setText(skills);
I am getting null response as when I execute this code. Please help and thanks in advance!
As I can see from the response, it is not returning an array or a list. However, as far as I have understood from your code, you are expecting to parse the response into a list.
The Freelancer pojo should look like the following.
public class FreeLancer {
public FreeLancerProfile freelancer;
}
If everything else is okay, it should work fine.
UPDATE:
The response should be bound to FreeLancer class, not to FreeLancerProfile class. I have shown an example, which might help. Please check.
public void onResponse(Call<FreeLancer> call, Response<FreeLancer> response) {
if (response.code() == 200) {
FreeLancer freelancer = response.body();
name = freelancer.getName();
email = freelancer.getEmail();
// Others ...
}
}
And in your FreelancerProfile pojo, you need to remove the List from the key_skills and other_skills as well. These are not lists as well.
private KeySkill key_skills;
private OtherSkill other_skills;

json to java Object using jackson

Hi i want to convert this json to json object in java so that i can pass it to http request to call an api
{
"aliasNaming": true,
"dataServiceType": "BROWSE",
"deviceName": "MyDevice",
"langPref": " ",
"maxPageSize": "2000",
"outputType": "VERSION1",
"password": "!jshjhsdhshdj",
"query": {
"autoClear": true,
"autoFind": true,
"condition": [
{
"controlId": "F4211.CO",
"operator": "EQUAL",
"value": [
{
"content": "00098",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.DCTO",
"operator": "EQUAL",
"value": [
{
"content": "SM",
"specialValueId": "LITERAL"
}
]
},
{
"controlId": "F4211.UPMJ",
"operator": "GREATER_EQUAL",
"value": [
{
"content": "01/01/17",
"specialValueId": "LITERAL"
}
]
}
],
"matchType": "MATCH_ALL"
},
"returnControlIDs": "F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP",
"targetName": "F4211",
"targetType": "table",
"token": "044biPNadxNVGhyAKdrImoniK98OOa2l86ZA63qCr4gE5o=MDIwMDA4LTIyNDU5MjUxMTY2MzY3NTA3MTRNeURldmljZTE1Mzc0MjYwMjAyNTk=",
"username": "Ali"
}
i have created 4 models using http://www.jsonschema2pojo.org.
those models just have getter setter in it. look something like this
#JsonProperty("aliasNaming")
private Boolean aliasNaming;
#JsonProperty("dataServiceType")
private String dataServiceType;
#JsonProperty("deviceName")
private String deviceName;
#JsonProperty("langPref")
private String langPref;
#JsonProperty("maxPageSize")
private String maxPageSize;
#JsonProperty("outputType")
private String outputType;
#JsonProperty("password")
private String password;
#JsonProperty("query")
private Query query;
#JsonProperty("returnControlIDs")
private String returnControlIDs;
#JsonProperty("targetName")
private String targetName;
#JsonProperty("targetType")
private String targetType;
#JsonProperty("token")
private String token;
#JsonProperty("username")
private String username;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("aliasNaming")
public Boolean getAliasNaming() {
return aliasNaming;
}
#JsonProperty("aliasNaming")
public void setAliasNaming(Boolean aliasNaming) {
this.aliasNaming = aliasNaming;
}
#JsonProperty("dataServiceType")
public String getDataServiceType() {
return dataServiceType;
}
#JsonProperty("dataServiceType")
public void setDataServiceType(String dataServiceType) {
this.dataServiceType = dataServiceType;
}
#JsonProperty("deviceName")
public String getDeviceName() {
return deviceName;
}
#JsonProperty("deviceName")
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
#JsonProperty("langPref")
public String getLangPref() {
return langPref;
}
#JsonProperty("langPref")
public void setLangPref(String langPref) {
this.langPref = langPref;
}
#JsonProperty("maxPageSize")
public String getMaxPageSize() {
return maxPageSize;
}
#JsonProperty("maxPageSize")
public void setMaxPageSize(String maxPageSize) {
this.maxPageSize = maxPageSize;
}
#JsonProperty("outputType")
public String getOutputType() {
return outputType;
}
#JsonProperty("outputType")
public void setOutputType(String outputType) {
this.outputType = outputType;
}
#JsonProperty("password")
public String getPassword() {
return password;
}
#JsonProperty("password")
public void setPassword(String password) {
this.password = password;
}
#JsonProperty("query")
public Query getQuery() {
return query;
}
#JsonProperty("query")
public void setQuery(Query query) {
this.query = query;
}
#JsonProperty("returnControlIDs")
public String getReturnControlIDs() {
return returnControlIDs;
}
#JsonProperty("returnControlIDs")
public void setReturnControlIDs(String returnControlIDs) {
this.returnControlIDs = returnControlIDs;
}
#JsonProperty("targetName")
public String getTargetName() {
return targetName;
}
#JsonProperty("targetName")
public void setTargetName(String targetName) {
this.targetName = targetName;
}
#JsonProperty("targetType")
public String getTargetType() {
return targetType;
}
#JsonProperty("targetType")
public void setTargetType(String targetType) {
this.targetType = targetType;
}
#JsonProperty("token")
public String getToken() {
return token;
}
#JsonProperty("token")
public void setToken(String token) {
this.token = token;
}
#JsonProperty("username")
public String getUsername() {
return username;
}
#JsonProperty("username")
public void setUsername(String username) {
this.username = username;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Now i want to set the values in these models by creating their respective objects and finally i got one main object with all the data. like this
Value Vobj1 = new Value();
Vobj1.setContent("00098");
Vobj1.setSpecialValueId("LITERAL");
List<Value> valueList1= new ArrayList<Value>();
valueList1.add(Vobj1);
Value Vobj2 = new Value();
Vobj2.setContent("SM");
Vobj2.setSpecialValueId("LITERAL");
List<Value> valueList2= new ArrayList<Value>();
valueList2.add(Vobj2);
Value Vobj3 = new Value();
Vobj3.setContent("01/01/17");
Vobj3.setSpecialValueId("LITERAL");
List<Value> valueList3= new ArrayList<Value>();
valueList3.add(Vobj3);
Condition Cobj1 = new Condition();
Cobj1.setControlId("F4211.CO");
Cobj1.setOperator("EQUAL");
Cobj1.setValue(valueList1);
Condition Cobj2 = new Condition();
Cobj2.setControlId("F4211.DCTO");
Cobj2.setOperator("EQUAL");
Cobj2.setValue(valueList1);
Condition Cobj3 = new Condition();
Cobj3.setControlId("F4211.UPMJ");
Cobj3.setOperator("GREATER_EQUAL");
Cobj3.setValue(valueList1);
List<Condition> conditionList1 = new ArrayList<Condition>();
conditionList1.add(Cobj1);
conditionList1.add(Cobj2);
conditionList1.add(Cobj3);
Query Qobj1= new Query();
Qobj1.setAutoClear(true);
Qobj1.setAutoFind(true);
Qobj1.setCondition(conditionList1);
Qobj1.setMatchType("MATCH_ALL");
JSONStructure obj=new JSONStructure();
obj.setAliasNaming(true);
obj.setDataServiceType("BROWSE");
obj.setDeviceName("MyDevice");
obj.setLangPref(" ");
obj.setMaxPageSize("2000");
obj.setOutputType("VERSION1");
obj.setPassword("!J0g3t6000");
obj.setQuery(Qobj1);
obj.setReturnControlIDs("F4211.DOCO|F4211.TRDJ|F4211.CRCD|F4211.AN8|F4211.DSC2|F4211.DSC1|F4211.LITM|F4211.LOTN|F4211.UORG|F4211.UPRC|F4211.AEXP");
obj.setTargetName("F4211");
obj.setTargetType("table");
obj.setToken(Token);
obj.setUsername("JOGET");
Now obj is my final object that i am going to pass to an http request and call the api and get the data from it. i want to make sure that my json is created correct, how am i suppose to print the all the data inside this object? and am i going correct with this approach?
if you use maven put gson into your pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
then print your object like this
System.out.println(new Gson().toJson(yourObj));
your object will print in json
I found two full working examples that is familiar with your case.
1) Using Gson refer to the tutorial Parse json string and java object into Gson tree model
2) Using Jackson refer to the tutorial Convert Java Object to/from JSON using JACKSON API
Hope this help.

Categories