I've a JSON which I want to deserialize to java object. I tried but failed to succeed. Really appreciate if somebody help it. I was getting below error.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// Note : vairable 'body' is the JSON string which I've shared below.
RpcResponse rs = mapper.readValue(body, RpcResponse.class);
Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of Result out of START_ARRAY token
{
"error": null,
"id": "12345",
"result": {
"inventory": [{
"history": [{
"when": "2012-08-30T07:28:51Z",
"changes": [{
"removed": "",
"added": "1",
"field_name": "qty"
},
{
"removed": "normal",
"added": "major",
"field_name": "popularity"
}],
"id": 474599,
"alias": null
}]
}
}
Here are the java classes
public class RpcResponse {
private String error;
private String id;
private Map<String, Result> result;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
public class Result {
private Map<String, List<Inventory>> inventory;
public Map<String, List<Inventory>> getBugs() {
return inventory;
}
public void setBugs(Map<String, List<Inventory>> inventory) {
this.inventory = inventory;
}
}
public class Inventory {
private String id;
private String alias;
private Map<String, List<History>> history;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public Map<String, List<History>> getHistory() {
return history;
}
public void setHistory(Map<String, List<History>> history) {
this.history = history;
}
}
public class History {
private String who;
private String when;
private Map<String, Changes> changes;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public Map<String, Changes> getChanges() {
return changes;
}
public void setChanges(Map<String, Changes> changes) {
this.changes = changes;
}
}
In RCP Response,
private Map<String, Result> result;
should just be
private Result result;
In Result,
private Map<String, List<Inventory>> inventory;
should be
private List<Inventory> inventory;
and in Inventory,
private Map<String, List<History>> history;
should be
private List<History> history;
In History, Map<String,Changes> should be a Collection<Changes>, etc
Related
I searched a lot in Google to find a way to use Nested Json Arrays with Retrofit, but it is useless
Most of what I found talks about using JSON Objects with retrofit
And my main issue is how to use the nested Array list inside call method to get data from the server
I have this
JSON
{
"orders": [
{
"ID": "1",
"OrderDate": "2020-07-01",
"order_details": [
{
"detail_ID": "1",
"description": "new order",
"items": [
{
"item_ID": "1",
"item_name": "milk",
"Quantity": "4",
"Price": "56.0",
"UnitOfMeasure": "unit"
},
{
"item_ID": "1",
"item_name": "nuts",
"Quantity": "6",
"Price": "500",
"UnitOfMeasure": "unit"
}
]
}
]
}
]
}
And those my other classes
Item.java
public class Item {
#SerializedName("item_ID")
#Expose
private String itemID;
#SerializedName("item_name")
#Expose
private String itemName;
#SerializedName("Quantity")
#Expose
private String quantity;
#SerializedName("Price")
#Expose
private String price;
#SerializedName("UnitOfMeasure")
#Expose
private String unit_Of_Measure;
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUnitOfMeasure() {
return unitOfMeasure;
}
public void setUnitOfMeasure(String unitOfMeasure) {
this.unitOfMeasure = unitOfMeasure;
}
}
Order.java
public class Order {
#SerializedName("orders")
#Expose
private List<Order_> orders = null;
public List<Order_> getOrders() {
return orders;
}
public void setOrders(List<Order_> orders) {
this.orders = orders;
}
}
OrderDetail.java
public class OrderDetail {
#SerializedName("detail_ID")
#Expose
private String detailID;
#SerializedName("description")
#Expose
private String description;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getDetailID() {
return detailID;
}
public void setDetailID(String detailID) {
this.detailID = detailID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Order_.java
public class Order_ {
#SerializedName("ID")
#Expose
private String iD;
#SerializedName("OrderDate")
#Expose
private String orderDate;
#SerializedName("order_details")
#Expose
private List<OrderDetail> orderDetails = null;
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public List<OrderDetail> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
}
ApiInterface.java
#GET("orders")
Call<Order> getAllOrders();
Now I want to get order_detail, item data inside this function
order.enqueue(new Callback<Order>() {
#Override
public void onResponse(Call<Order> call, Response<Order> response) {
if(response.isSuccessful()){
//here ..................
}
}
#Override
public void onFailure(Call<TaskResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
}
});
I will be so grateful who can help me
I am trying below code to convert below JSON to POJO using ObjectMapper class of Jackson but it's throwing exception. Could anyone help me to resolve this issue.
Actually JSON is given by UI so can't change format of it. I need to parse this JSON to java object using Jackson library.
JSON: data.json
{
"0": {
"location": "6",
"userType": "1",
"isActive": "1",
"userId": "Shailesh#gmail.com"
},
"1": {
"location": "7",
"userType": "2",
"isActive": "1",
"userId": "Vikram#gmail.com"
}
}
DTOs:
public class UsersList {
List<UserDetails> users;
}
public class UserDetails {
private String userId;
private String location;
private String userType;
private String isActive;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
}
Test Class: HandlerUtil
import java.io.IOException;
import java.io.InputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mcmcg.ams.lambda.model.UserDetails;
public class HandlerUtil {
private static final Logger LOG = LogManager.getLogger(HandlerUtil.class);
private HandlerUtil() {
}
public static void main(String[] args) {
try (InputStream instream = HandlerUtil.class.getClassLoader().getResourceAsStream("data.json")) {
UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);
System.out.println(sample.toString());
} catch (IOException ex) {
LOG.error("Exception occurred while laoding data.json file : ", ex);
}
}
}
Exception:
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
You can use ObjectMapper.readValue() method of jackson.
I think your solution will be like this :
String jsonBody = yourJson;
ObjectMapper objectMapper = new ObjectMapper();
try {
UserDetailsMapDao userDetailsMapDao = objectMapper
.readValue(jsonBody, UserDetailsMapDao.class);
} catch (JsonParseException e) {
// TODO Exception Handling
} catch (JsonMappingException e) {
// TODO Exception Handling
} catch (IOException e) {
// TODO Exception Handling
}
Your Daos will be like this :
public class UserDetailsMapDao {
private Map<String, UserDetails> userDetailsMap;
public String getUserDetailsMap() {
return userDetailsMap;
}
public void setUserDetailsMap(String userDetailsMap) {
this.userDetailsMap = userDetailsMap;
}
}
public class UserDetails {
private String userId;
private String location;
private String userType;
private String isActive;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
}
The JSON is in format of Map<String, UserDetails> take a look at that, key 0 has user "Shailesh#gmail.com" and key 1 with "Vikram#gmail.com"
TypeReference<HashMap<String,UserDetails>> typeRef
= new TypeReference<HashMap<String,UserDetails>>() {};
HashMap<String,UserDetails> sample = new ObjectMapper()
.readValue(instream, typeRef);
If using jackson use #JsonAnySetter
public class UsersList {
private Map<String, UserDetails> users = new HashMap<>();
#JsonAnySetter
public void setUsers(String name, UserDetails value) {
this.addressDetails.put(name, value);
}
}
And then map it to UserDetails
UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);
Firstly, before you can deserialize your json string to DTOs, the DTOs should contain no-argument constructor, getters and setters.
Your currect DTOs would match a string like the one below.
{
"users": [
{
"location": "6",
"userType": "1",
"isActive": "1",
"userId": "Shailesh#gmail.com"
},
{
"location": "7",
"userType": "2",
"isActive": "1",
"userId": "Vikram#gmail.com"
}
]
}
The DTO that would match the string example provided above would be like the following.
public class UsersList {
UserDetails zero;
UserDetails one;
public UsersList() {
}
public UserDetails getZero() {
return zero;
}
public void setZero(final UserDetails zero) {
this.zero = zero;
}
public UserDetails getOne() {
return one;
}
public void setOne(final UserDetails one) {
this.one = one;
}
}
Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
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;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();
This question already has answers here:
Retrofit 2: Get JSON from Response body
(14 answers)
Closed 5 years ago.
How to read this response from retrofit and store to java class and access somewhere ??
{
"user": {
"__v": 0,
"updated_at": "2017-11-08T12:07:46.729Z",
"created_at": "2017-11-08T12:07:46.729Z",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QzIiwidXNlcmlkIjozLCJlbWFpbCI6ImFydWwzQHRlc3QuY29tIiwiYWNjZXNzX2xldmVsIjoiQWRtaW4iLCJfaWQiOiI1YTAyZjM5Mjk5OGM4OTI3MjQxYTQ3N2YiLCJncm91cHMiOlt7ImlkIjoxLCJuYW1lIjoiZGlhbGVyIiwiX2lkIjoiNThiM2JmODI5ZTg2MDFjMDVlNzIxNjI3In1dfQ.VKEt1JoXoL_xfRDrrFK-jVj8zC23j4sqZTT2S3HGMbc",
"username": "test3",
"userid": 3,
"email": "arul3#test.com",
"access_level": "Admin",
"_id": "5a02f392998c8927241a477f",
"groups": [{
"id": 1,
"name": "dialer",
"_id": "58b3bf829e8601c05e721627"
}]
}
}
Create classes from pojo like that then parse to retrofit Convert json response to classes
public class MyPojo{
private User user;
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
}
User Class:
public class User{
private String username;
private String updated_at;
private String _id;
private String access_level;
private String email;
private String token;
private String userid;
private String __v;
private String created_at;
private Groups[] groups;
public String getUsername ()
{
return username;
}
public void setUsername (String username)
{
this.username = username;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getAccess_level ()
{
return access_level;
}
public void setAccess_level (String access_level)
{
this.access_level = access_level;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getToken ()
{
return token;
}
public void setToken (String token)
{
this.token = token;
}
public String getUserid ()
{
return userid;
}
public void setUserid (String userid)
{
this.userid = userid;
}
public String get__v ()
{
return __v;
}
public void set__v (String __v)
{
this.__v = __v;
}
public String getCreated_at ()
{
return created_at;
}
public void setCreated_at (String created_at)
{
this.created_at = created_at;
}
public Groups[] getGroups ()
{
return groups;
}
public void setGroups (Groups[] groups)
{
this.groups = groups;
}
}
Groups Class:
public class Groups{
private String id;
private String _id;
private String name;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}}
Now follow that put your classes and get desire response Retrofit Json response
I am having my collection like below:
{
"_id" : NumberLong(366),
"file" : "xyz",
"meta" : [{
"owner" : "user123",
"rating": "A"
}]
}
I want to sort the query result based on owner
I have tried the below code but sorting is not working
Can anyone help me on this.
query = new Query();
query.addCriteria(Criteria.where("meta.rating").is("A"));
query.with(new Sort(Sort.Direction.ASC, "meta.owner"));
mongoOperations.find(query, Test.class);
My Test Class:
Here i am having List which is another model
#Document(collection = "Test_Data")
public class Test{
#Id
private long id;
private String file;
private List<MetaList> meta;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public List<MetaList> getMeta() {
return meta;
}
public void setMeta(List<MetaList> meta) {
this.meta= meta;
}
}
My MetaList class:
public class MetaList{
private String owner;
private String rating;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner= owner;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating= rating;
}
}