JSON String
{
"order":{
"address":{
"city":"seattle"
},
"orderItem":[
{
"itemId":"lkasj",
"count":2
},
{
"itemId":"ldka",
"count":3
}
]
}
}
Order Class
public class Order {
private OrderItem[] orderItems;
private CustomerAddress address;
Order(OrderItem[] orderItems, CustomerAddress address ) {
this.orderItems = orderItems;
this.address = address;
}
public OrderItem[] getOrderItems() {
return orderItems;
}
public void setOrderItems(OrderItem[] orderItems) {
this.orderItems = orderItems;
}
public CustomerAddress getAddress() {
return address;
}
public void setAddress(CustomerAddress address) {
this.address = address;
}
}
My OrderItem class
package com.cbd.backend.model;
import org.springframework.data.annotation.Id;
public class OrderItem {
#Id
private String id;
private String itemId;
private String count;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
unit Test that blows up
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
Unit test to demonstrate issue
package com.cbd.backend.model;
import com.google.gson.Gson;
import org.junit.Test;
import static org.junit.Assert.*;
public class OrderTest {
Gson gson = new Gson();
#Test
public void gsonToOrder() {
Order order = gson.fromJson( a, Order.class );
assertNotNull(order);
assertNotNull(order.getOrderItems()[0]);
}
private final String a = "{ \"order\": { \"address\": { \"city\": \"seattle\" },\"orderItem\":[{ \"itemId\":\"lkasj\", \"count\":2 }, { \"itemId\":\"ldka\", \"count\":3 } ] } }";
}
Should I be using something other than gson or am i constructing this incorrectly
There are two problems in your code:
The root element of your JSON is "order", but the class does not have a property with this name. Try changing you model or just removing the element from the JSON.
There is a mismatch in the name of the "orderItem" property. It is plural in the class, but singular in the JSON.
To sum it up, the following JSON will work without any changes to the code.
{
"address":{
"city":"seattle"
},
"orderItems":[
{
"itemId":"lkasj",
"count":2
},
{
"itemId":"ldka",
"count":3
}
]
}
Also, "count" as it appears in the JSON seems to be numeric, so you might want to change the type of OrderItem.count to int or java.lang.Integer.
Related
I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)
Below is my JSON data. I want to convert this to POJOs to store the Name,id,profession in a header table and the respective Jsonarray field in a child table.
JSON:
{
"Name": "Bob",
"id": 453345,
"Profession": "Clerk",
"Orders": [
{
"Item": "Milk",
"Qty": 3
},
{
"Item": "Bread",
"Qty": 3
}
]
}
Entity classes:
public class User {
private String name;
private Integer id;
private String Profession;
private JsonArray Orders;
private UserCart userCart;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProfession() {
return Profession;
}
public void setProfession(String profession) {
Profession = profession;
}
public JsonArray getOrders() {
return Orders;
}
public void setOrders(JsonArray orders) {
Orders = orders;
}
public UserCart getUserCart() {
return userCart;
}
public void setUserCart(UserCart userCart) {
this.userCart = userCart;
}
}
public class UserCart {
private String item;
private Integer qty;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
}
But when I do below; I get error
Cannot deserialize instance of org.json.JSONArray out of START_ARRAY
token
User user = new User();
JsonNode data = new ObjectMapper().readTree(jsonString);
user = headerMap.readValue(data.toString(), User.class);
How do I go about assigning the entire JSON to both the Java objects ?
Use List<UserCart> for array data in json and use #JsonProperty for mapping different json node name to java object field. No need to use extra field (JsonArray Orders) anymore.
#JsonProperty("Orders")
private List<UserCart> userCart;
I know there are a few questions on stackoverflow regarding this problem. But I have have been spending hours trying to resolve this error without any success.
I am using the mysql database to store the values.
I keep on getting the error message from the
com.example.springboot.Recipe file.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
private Integer cooktime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getCookingtime() {
return cooktime;
}
public void setCookingtimeime(Integer cooktime) {
this.cooktime = cooktime;
}
public Integer getPreparationtime() {
return preptime;
}
public void setPreparationtime(Integer preptime) {
this.preptime = preptime;
}
}
Main Controller:
#PutMapping("/recipes/edit/{id}")
void updateRecipe2(#PathVariable int id, #RequestBody Recipe recipe ) {
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setTitle(recipe.getTitle());
System.out.println("sss " + recipe.getname());
System.out.println("change");
recipeRepository.save(recipe_);
}
service.ts:
updateRecipe2 (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe2 gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
as soon as the user clicks save this functions saves the changes made.
I hope the code snippets that I provided are enough to help solve the problem.
Thank you in advance.
I am building a rest api with spring boot and I am using angularjs as it's frontend. I am pretty new to web-development.
You are sending a list of recipes to an api endpoint that expects a single recipe object.
Your options are:
Send only one recipe object at a time, for example:
this.recipeService.updateRecipe2(id, this.recipes[0])
OR: create a new API endpoint to accept a list of recipes, to edit them in "batch"
#PutMapping("/recipes/edit")
void updateRecipes(#RequestBody List<Recipe> recipe ) {
my Example:
Use:
#PostMapping
Code:
public void setTransacciones(List<Transacciones> transacciones) {
this.transacciones = transacciones;
}
CodeBean:
public class Transacciones {
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
}
Post(raw):
{
"transacciones" : [ {"text" : "1"}, {"text" : "2"} ]
}
Result:
{
"transacciones": [
{
"transaccionId": 2,
"text": "1"
},
{
"transaccionId": 3,
"text": "2"
}
]
}
BINGO!!
I'm trying to parse a JSON like this
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"customer_id": "some-customer-id",
"id": 5,
"is_active": true,
"product_code": "some-product-code",
"resource_uri": "/api/v1/aws-marketplace/5/",
"support_subscription_id": "22"
}
]
}
generated for http://www.jsonschema2pojo.org I got his Java clases
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AwsMarketplace {
#SerializedName("meta")
#Expose
private Meta meta;
#SerializedName("objects")
#Expose
private List<Object> objects = null;
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
public List<Object> getObjects() {
return objects;
}
public void setObjects(List<Object> objects) {
this.objects = objects;
}
}
Meta class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Meta {
#SerializedName("limit")
#Expose
private int limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private int offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total_count")
#Expose
private int totalCount;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
Object class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Object {
#SerializedName("customer_id")
#Expose
private String customerId;
#SerializedName("id")
#Expose
private int id;
#SerializedName("is_active")
#Expose
private boolean isActive;
#SerializedName("product_code")
#Expose
private String productCode;
#SerializedName("resource_uri")
#Expose
private String resourceUri;
#SerializedName("support_subscription_id")
#Expose
private String supportSubscriptionId;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isIsActive() {
return isActive;
}
public void setIsActive(boolean isActive) {
this.isActive = isActive;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getResourceUri() {
return resourceUri;
}
public void setResourceUri(String resourceUri) {
this.resourceUri = resourceUri;
}
public String getSupportSubscriptionId() {
return supportSubscriptionId;
}
public void setSupportSubscriptionId(String supportSubscriptionId) {
this.supportSubscriptionId = supportSubscriptionId;
}
}
But when trying to deserialise with this func
Type localVarReturnType = new TypeToken<List<InstanceCreatorForAwsMarketplace>>(){}.getType();
ApiResponse<List<InstanceCreatorForAwsMarketplace>> responseFromApiCleint = apiClient.execute(newCall, localVarReturnType);
I get the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Any idea what might be the issue? This looks like a fairly simple json that the rest service returns, but I have not been able to get it work, any help would be greatly appreciated.
Right after I had written the question, I found out the answer, of course the top level class should not be a list, just the class it self. But I have a secondary question, can the three mapper classes be mounted into one class, just a cosmetic issue?
I'm using Jackson as part of a spring boot app. I am turning JSON into Java, and I am getting this error. I did some research, but I still don't understand what is going wrong or how to fix it.
Here is the JSON fragment:
"dataBlock": {
"sections": [
{
"info": "",
"prompt": "",
"name": "First Section",
"sequence": 0,
"fields": [],
"gatingConditions": [],
"guid": "480d160c-c34f-4022-97b0-e8a1f28c49ae",
"id": -2
}
],
"prompt": "",
"id": -1,
"name": ""
}
So my Java object for this "dataBlock" element:
public class DataBlockObject {
private int id;
private String prompt;
private String name;
private List<SectionObject> sections;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<SectionObject> getSections() {
return sections;
}
public void setSections(List<SectionObject> sections) {
this.sections = sections;
}
}
And the Section object is this:
public class SectionObject {
private int id;
private String name;
private String prompt;
private String info;
private int sequence;
private List<FieldObject> fields;
private List<GatingConditionObject> gatingConditions;
private String guid;
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 String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
public List<FieldObject> getFields() {
return fields;
}
public void setFields(List<FieldObject> fields) {
this.fields = fields;
}
public List<GatingConditionObject> getGatingConditions() {
return gatingConditions;
}
public void setGatingConditions(List<GatingConditionObject> gatingConditions) {
this.gatingConditions = gatingConditions;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
}
So it seems to me that Jackson would make a DataBlockObject, map the obvious elemenets, and create an array that I have clearly marked as a List named sections. -- just like the JSON shows.
Now the error is:
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "sections" (class com.gridunity.workflow.bean.json.SectionObject), not marked as ignorable (8 known properties: "gatingConditions", "sequence", "prompt", "fields", "id", "info", "guid", "name"])
Now according to that error it would seem that one of my 8 elements should be named "sections" - But that's not one of my elements. It clearly has a problem with my List of Sections, but I cant figure out what it is.
Can someone explain WHY this is happening, especially sence it looks like I have my structure correct, and how to fix this. I have seen this on other posts:
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
But that seems incredibly wrong as I know all of my properties.
It looks like the JSON itself has another sections field in one or more of the dataBlock.sections items. If you don't have control over the construction of the JSON object, you'll need to add a #JsonIgnoreProperties annotation on the SectionObject class so that when the JSON object has fields that aren't specified in the POJO, it won't throw an error during deserialization.
#JsonIgnoreProperties(ignoreUnknown = true)
public class SectionObject {
// class members and methods here
}