How to use Gson fromJson in this situation? - java

I want to convert json to Java Obejct using Gson.
For example, Json structure is ...
{
"title": "title",
"product" : [
{
"key": "product1",
"value": [{
"valueName": "productValue1"
}]
"date" : "2022-10-11"
},
{
"key": "product2",
"value": []
},
"date" : "2022-10-11"
]
}
I made DTOs like...
public Class ProductDTO {
String title;
List<Product> product;
}
public Class Product {
String key;
List<Value> value;
}
public Class Value {
String valueName;
}
And
// payload: String
Gson gson = new Gson();
ProductDTO productDTO = gson.fromJson(payload, ProductDTO.class);
When executing fromJson, I had MalformedJsonException.
In json, value List size == 0 for "key": "product2"
But I have String valueName attribute in Value Class.
How can I resolve this problem?

I think your model classes will be like that
public class Product {
#SerializedName("key")
#Expose
private String key;
#SerializedName("value")
#Expose
private List<Value> value = null;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
public class ProductDTO {
#SerializedName("title")
#Expose
private String title;
#SerializedName("product")
#Expose
private List<Product> product = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
public class Value {
#SerializedName("valueName")
#Expose
private String valueName;
public String getValueName() {
return valueName;
}
public void setValueName(String valueName) {
this.valueName = valueName;
}
}

Related

How to Get Json object and Json Array in Same KEY by retrofit for android

I am getting JSON Object when their is only one response(items) or JSON Array response but i want to array and object response.How to handle JSON Response?
JSON ARRAY when their is more than one items.And JSON OBJECT when their is only one items
.
{
"product":[
{
"items":[
{
"name":"foo",
"title":"toy"
},
{
"name":"foo",
"title":"toy"
}
]
},
{ "items":
{
"name":"foo",
"title":"toy"
}
}
]
}
First create model for this json Response using json to p
public class Example {
#SerializedName("product")
#Expose
private List<Product> product = null;
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
public class Item {
#SerializedName("name")
#Expose
private String name;
#SerializedName("title")
#Expose
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Product {
#SerializedName("items")
#Expose
private List<Item> items = null;
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Pass this Exmaple class into your response like
Call and get the data usning model

Fetching Nested JSON Arrays with retrofit?

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

Json inside json not working in spring boot

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.

JSON de-serialization using jackson

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

GSOn error Expected a string but was BEGIN_OBJECT when parsing JSON response

I retrieve a JSON result from an API :
[{
"oid": "axd7wtlk6xd2fbwlc5wk",
"id": "aazzzza",
"name": "aazzaa",
"logo": {
"type": 0,
"data": "iVB.............5CYII="
},
"timestamp": 1438608571013,
"email": "contact#azzaa.net",
"modified": "test",
"url": "http://www.azzaa.net"
},
{
"oid": "quj3dzygfwygl5uxsbxk",
"name": "KZZZ",
"modified": "test",
"timestamp": 1438854099511,
"id": "kess"
},...]
but when I try to map to a customer object I get the error Expected a string but was BEGIN_OBJECT :
response = webService.RequestGet(url, header);
result = null;
try {
result = new JSONArray(response);
Utils.LogWarning(response);
} catch (JSONException e) {
Utils.LogError("Could not load json response", e);
}
Type customerType = new TypeToken<Collection<Customer>>() {
}.getType();
ArrayList<Customer> alCustomers = null;
alCustomers = new Gson().fromJson(result.toString(), customerType);
Here is my Customer class :
public class Customer implements Serializable {
private String id = "";
private String name = "";
private String email = "";
private String url = "";
private String address = "";
private String stamp = "";
//private transient String logo = "";
private long timestamp = 0L;
private String modified = "";
...
}
I have been through a lot of answers regarding this problem that I have also for other types of objects, but I can't find a working solution.
Create a modal with the values of JSON result like
public class Customer {
private String oid;
private String id;
private String name;
private String timestamp;
private String email;
private String modified;
private String url;
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Logo getLogo() {
return logo;
}
public void setLogo(Logo logo) {
this.logo = logo;
}
private Logo logo;
}
public class Logo {
private int type;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
private String data;
}
Gson gson = new Gson();
Type listType = new TypeToken<List<Customer>>(){}.getType();
List<Customer> customer= (List<Customer>) gson.fromJson(jsonOutput, listType);

Categories