Why can't I assign a value to status during JSON response. How to read the integer status? Thanks for help !
Model:
public class JsonResponse {
public String code;
public Integer status;
public String getCode() { return code; }
public Integer getStatus() { return status; }
}
Response JSON:
{
"code": "jwt_auth_valid_token",
"data": {
"status": 200
}
}
Result: getStatus(): Null
Because status is inside object called data so you should create data class that will save the status for example
public class Data {
public int status;
}
public class JsonResponse {
public String code;
public Data data;
public String getCode() { return code; }
public Integer getStatus() { return data.status;}
}
as answered Marwa Eltayeb but we can modify the answer more with :
public class JsonResponse {
#SerializedName("code")
public String code;
#SerializedName("data")
public Data data;
public String getCode() {
return code;
}
public Data getData() {
return data;
}
public class Data {
#SerializedName("status")
public int status;
public int getStatus() {
return status;
}
}
}
Related
I am trying to use JSON inside a JSON request.
for example:
{
"name":"newdeeeepaajlf",
"category":"fsafaa",
"jsonData":{
"a":"value"
}
}
now when I am trying to get it in my DTO which has
private JSONObject jsonData;
it gets converted in a blank JSON
{}
I am stuck in this.
We can use map to convert the data
public class TestModel {
private String name;
private String category;
private Map<String, Object> jsonObj;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Map<String, Object> getJsonObj() {
return jsonObj;
}
public void setJsonObj(Map<String, Object> jsonObj) {
this.jsonObj = jsonObj;
}
}
and use above class from controller like below
#PostMapping("/test")
public boolean test(#RequestBody TestModel model) {
System.out.println(model.getCategory());
System.out.println(model.getName());
JSONObject jsonObj = new JSONObject(model.getJsonObj());
System.out.println(jsonObj);
return true;
}
For request
{
"category":"json",
"name":"name",
"jsonObj": {
"a": "value"
}
}
it will print
json
name
{a=value}
you have a error in json if you have json something like below.
{
"name": "newdeeeepaajlf",
"category": "fsafaa",
"jsonData": {
"a": "value"
}
}
you can use this as a class
public class Codebeautify {
private String name;
private String category;
JsonData jsonDataObject;
// Getter Methods
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public JsonData getJsonData() {
return jsonDataObject;
}
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setCategory(String category) {
this.category = category;
}
public void setJsonData(JsonData jsonDataObject) {
this.jsonDataObject = jsonDataObject;
}
}
public class JsonData {
private String a;
// Getter Methods
public String getA() {
return a;
}
// Setter Methods
public void setA(String a) {
this.a = a;
}
}
also json within json is working with in spring boot its a very common scenario. use ObjectMapper to map json with class.
The parsing is successful but problem is ,it is taking loggedinClients only,ActiveClients not getting in retrofit , how can we parse array under array and with no object name?
{
"status": 200,
"success": true,
"messages": "",
"result": [
[
{
"LoggedinClients": 1
}
],
[
{
"ActiveClients": 0
}
]
]
}
partly Related Code:
public class OnlineInfoResponse {
#SerializedName("result")
#Expose
private List<List<OnlineInfoLoggedInResult>> lstLists = null;
public List<List<OnlineInfoLoggedInResult>> getLstLoggedIn() {
return lstLists;
}
public void setLstLists(List<List<OnlineInfoLoggedInResult>> lstLists) {
this.lstLists = lstLists;
}
OnlineInfoLoggedInResult.java
public class OnlineInfoLoggedInResult {
#SerializedName("LoggedinClients")
#Expose
private int loggedinClients;
public int getLoggedinClients() {
return loggedinClients;
}
public void setLoggedinClients(int loggedinClients) {
this.loggedinClients = loggedinClients;
}
#SerializedName("ActiveClients")
#Expose
private int activeClients;
public int getActiveClients() {
return activeClients;
}
public void setActiveClients(int activeClients) {
this.activeClients = activeClients;
}
}
this i got parsing from jsonschema.I am having problem in nested jsonarray.
You should generate the following POJO
public class YourPojoName {
private float status;
private boolean success;
private String messages;
List <List< Object> > result = new ArrayList < ArrayList<Object> > ();
// Getter Methods
public float getStatus() {
return status;
}
public boolean getSuccess() {
return success;
}
public String getMessages() {
return messages;
}
// Setter Methods
public void setStatus(float status) {
this.status = status;
}
public void setSuccess(boolean success) {
this.success = success;
}
public void setMessages(String messages) {
this.messages = messages;
}
}
public class abbb {
#Expose
#SerializedName("result")
private List<List<Result>> result;
#Expose
#SerializedName("messages")
private String messages;
#Expose
#SerializedName("success")
private boolean success;
#Expose
#SerializedName("status")
private int status;
public List<List<Result>> getResult() {
return result;
}
public void setResult(List<List<Result>> result) {
this.result = result;
}
public String getMessages() {
return messages;
}
public void setMessages(String messages) {
this.messages = messages;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static class Result {
#Expose
#SerializedName("LoggedinClients")
private int LoggedinClients;
#Expose
#SerializedName("ActiveClients")
private int active_clients;
//genetrate getter setter
}
}
Iam trying to get Status and message tag info using java 1.7
Please any guide me ,
Thanks in advance
<API version="0.0">
<response>
<operation name="ADD">
<result>
<statuscode>200</statuscode>
<status>Success</status>
<message> successfully</message>
</result>
<Details type="ADD"/>
</operation>
</response>
</API>
This is not a JSON response that you are getting, it's an XML response,
you just need to convert the XML response to POJO class and use the POJO class instead.
Here is how the POJO class will look like
public class MyPojo{
private API API;
public API getAPI() {
return API;
}
public void setAPI(API API) {
this.API = API;
}
}
now MyPojo will contain another class named API
public class API {
private Response response;
private String version;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
now the API class contains another class called Response
public class Response {
private Operation operation;
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
Now the Response class is containing another class called Operation
public class Operation {
private Result result;
private Details Details;
private String name;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Details getDetails() {
return Details;
}
public void setDetails(Details Details) {
this.Details = Details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you guessed it the Operation class is containing two classes Details and Result
Here is the Result class that is containing the status and message you want to access
public class Result {
private String message;
private String status;
private int statuscode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getStatuscode() {
return statuscode;
}
public void setStatuscode(int statuscode) {
this.statuscode = statuscode;
}
}
Here is the Details class
public class Details {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
finally, you can access the status and message by creating an object from MyPojo class like this:
String message = myPojo.getAPI().getResponse().getOperation().getResult().getMessage();
String status = myPojo.getAPI().getResponse().getOperation().getResult().getStatus();
you can use this online converter to convert XML/JSON to POJO.
I hope my answer was helpful :)
I am using Retrofit 2 to consume an JSON API, I have the following JSON structure
{
"data": {
"id": 1,
"name": "Josh"
}
}
My User POJO looks like:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And my User interface
#GET("/api/v1/me")
Call<User> me();
But I when I try and do response.body().getName() I get a null pointer exception.
The code which is making the request
UserService userService = ServiceGenerator.createService(UserService.class)
Call<User> call = userService.me();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getName().toString());
}
}
#Override
public void onFailure(Throwable t) {
Log.i("hello", t.getMessage());
}
});
You should create the POJO classes as follows:
POJO for json response:
public class User {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
POJO for internal Data:
public class Data {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Than use response.body().getData().getName() to access name in response.
public class Data {
private User data;
public String getData() {
return data;
}
public void setName(User data) {
this.data = data;
}
}
Access it like this
public void onResponse(Response<Data> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getData().getName().toString());
}
}
java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));