Jackson JSON User Group

JSON in Java the Right Way -- Action, Jackson!

I experimented with the example in JacksonInFiveMinutes and found this issue.  When I change the name of the field to Name in the example I keep getting this error

org.codehaus.jackson.map.JsonMappingException: Unrecognized field "Name" (Class JacksonTest.User), not marked as ignorable
 at [Source: src\JacksonTest\user.json; line: 2, column: 3]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:159)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:247)
    at org.codehaus.jackson.map.deser.StdDeserializer.reportUnknownProperty(StdDeserializer.java:366)
    at org.codehaus.jackson.map.deser.StdDeserializer.handleUnknownProperty(StdDeserializer.java:352)
    at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:542)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:401)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:286)
    at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:107)
    at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:84)
    at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:24)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1081)
    at JacksonTest.JacksonJsonTest.main(JacksonJsonTest.java:18)

but if I put the name back to lower case (name) it works perfectly.

My problem is that I am writing a client for a RESTful service and the fields are a mix of uppercase and lowercase.  All of the fields start with a uppercase.

How can I read these fields?

example
{
  "Name" : { "First" : "Joe", "Last" : "Sixpack" },
  "Gender" : "MALE",
  "Verified" : false,
  "UserImage" : "Rm9vYmFyIQ=="
}

Views: 9363

Reply to This

Replies to This Discussion

Simplest way would be to use @JsonProperty annotation, like so:

@JsonProperty("Name")
public void setName(String n) {
// ...
}

the reason "name" is expected otherwise is that this is the usual Java Bean naming convention.
Hello....I've just started out using Jackson JSON and i'm having difficulties getting the data binding portion to work. Here is my code:

I've also included my test JSON Data below. Any help is greatly appreciated!

import java.util.Calendar;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@SuppressWarnings("unused")
@JsonAutoDetect()
public class OrderForm {
// private static Logger logger = Logger.getLogger(OrderForm.class);

private static final long serialVersionUID = 2739167372182198247L;

//private static Map orders_export;
private static OrdersExport[] orders_export = null;
private static Info info[] = null;
private static Object totals[] = null;
private static Products products[] = null;
private static Insertions insertions[] = null;
private static Attributes attributes[] = null;
private static Customer customer[] = null;
private static CSR customer_service_rep[] = null;

private static String _id = "";
private static String _action = "";
private static String _datePurchased = "";
private static String _lastModified = "";

// Object used to store Orders
public static class OrdersExport {
@SuppressWarnings("unchecked")
private Vector info[];

@SuppressWarnings("unchecked")
@JsonSerialize
@JsonProperty("orders_export")
public Vector[] getOrders_Export() {
return info;
}
@SuppressWarnings("unchecked")
@JsonDeserialize
@JsonProperty("orders_export")
public void setOrders_Export(Vector[] s) {
info = s;
}
}

// Object used to store Order Information
public static class Info {
private String order_id, date_purchased, orders_status, last_modified;

public String getOrderId() {
return order_id;
}
public void setOrderId(String s) {
order_id = s;
}

public String getDatePurchased() {
return date_purchased;
}
public void setDatePurchased(String s) {
date_purchased = s;
}

public String getOrderStatus() {
return orders_status;
}
public void setOrderStatus(String s) {
orders_status = s;
}

public String getLastModified() {
return last_modified;
}
public void setLastModified(String s) {
last_modified = s;
}

}

// Object used to store Order Products
public static class Products {
private String product_id, op_id, name, order_product_status_id, vendor, price, final_price;
private Object[] insertions;

public String getProductId() {
return product_id;
}
public void setProductId(String s) {
product_id = s;
}

public String getOpId() {
return op_id;
}
public void setOpId(String s) {
op_id = s;
}

public String getName() {
return name;
}
public void setName(String s) {
name = s;
}

public String getOrderProductStatusId() {
return order_product_status_id;
}
public void setOrderProductStatusId(String s) {
order_product_status_id = s;
}

public String getVendor() {
return vendor;
}
public void setVendor(String s) {
vendor = s;
}

public String getPrice() {
return price;
}
public void setPrice(String s) {
price = s;
}

public String getFinalPrice() {
return final_price;
}
public void setFinalPrice(String s) {
final_price = s;
}

public Object[] getInsertions() {
return insertions;
}
public void setInsertions(String[] s) {
insertions = s;
}

}

// Object used to store Product Insertions
public static class Insertions {
private String package_count, order_xcid, business_naics, rev_rec_xcid, orders_product_id;
private Object[] attributes;

public String getPackageCount() {
return package_count;
}
public void setSetPackageCount(String s) {
package_count = s;
}

public String getOrderXcid() {
return order_xcid;
}
public void setOrderXcid(String s) {
order_xcid = s;
}

public String getBusinessNaics() {
return business_naics;
}
public void setBusinessNaics(String s) {
business_naics = s;
}

public String getRevRecXcid() {
return rev_rec_xcid;
}
public void setRevRecXcid(String s) {
rev_rec_xcid = s;
}

public String getOrdersProductId() {
return orders_product_id;
}
public void setOrdersProductId(String s) {
orders_product_id = s;
}

public Object[] getAttributes() {
return attributes;
}
public void setAttributes(Object[] s) {
attributes = s;
}

}

// Object used to store Insertion Attributes
public static class Attributes {
private String products_name, total_price, industry_name, dfw_regions, duration, campaign_date_range, attribute_package;

public String getProductName() {
return products_name;
}
public void setProductName(String s) {
products_name = s;
}

public String getTotalPrice() {
return total_price;
}
public void setTotalPrice(String s) {
total_price = s;
}

public String getIndustryName() {
return industry_name;
}
public void setIndustryName(String s) {
industry_name = s;
}

public String getDFWRegions() {
return dfw_regions;
}
public void setDFWRegions(String s) {
dfw_regions = s;
}

public String getDuration() {
return duration;
}
public void setDuration(String s) {
duration = s;
}

public String getCampaignDateRange() {
return campaign_date_range;
}
public void setCampaignDateRange(String s) {
campaign_date_range = s;
}

public String getAttributePackage() {
return attribute_package;
}
public void setAttributPackage(String s) {
attribute_package = s;
}

}

// Object used to store Customer Information
public static class Customer {
private String cust_id, company, street_address, suburb, city, postcode, state,
telephone, naics_code, naics_name, account_number, email;
Object[] country ;

public String getCustomerId() {
return cust_id;
}
public void setCustomerId(String s) {
cust_id = s;
}

public String getCompanyName() {
return company;
}
public void setCompanyName(String s) {
company = s;
}

public String getCompanyStreetAddress() {
return street_address;
}
public void setCompanyStreetAddress(String s) {
street_address = s;
}

public String getSuburb() {
return suburb;
}
public void setSuburb(String s) {
suburb = s;
}

public String getCity() {
return city;
}
public void setCity(String s) {
city = s;
}

public String getPostalCode() {
return postcode;
}
public void setPostalCode(String s) {
postcode = s;
}

public String getState() {
return state;
}
public void setState(String s) {
state = s;
}

public String getTelephone() {
return telephone;
}
public void setTelephone(String s) {
telephone = s;
}

public String getNaicsCode() {
return naics_code;
}
public void setNaicsCode(String s) {
naics_code = s;
}

public String getNaicsName() {
return naics_name;
}
public void setNaicsName(String s) {
naics_name = s;
}

public String getAccountNumber() {
return account_number;
}
public void setAccountNumber(String s) {
account_number = s;
}

public String getEmail() {
return email;
}
public void setEmail(String s) {
email = s;
}

}

// Object used to store Country Information
public static class Country {
private String country;

public String getCountry() {
return country;
}
public void setCountry(String s) {
country = s;
}

}

// Object used to store CSR Information
public static class CSR {
private String user_first_name, user_last_name, user_name, phone_number;

public String getUserFirstName() {
return user_first_name;
}
public void setUserFirstName(String s) {
user_first_name = s;
}

public String getUserLastName() {
return user_last_name;
}
public void setUserLastName(String s) {
user_last_name = s;
}

public String getUserNameEmail() {
return user_name;
}
public void setUserNameEmail(String s) {
user_name = s;
}

public String getUserPhoneNumber() {
return phone_number;
}
public void setUserPhoneNumber(String s) {
phone_number = s;
}

}




{"orders_export":
[

{
"info":{"orders_id":"250","date_purchased":"2010 05 18 16 10 50","orders_status":"Pending","last_modified":null},
"totals":[],
"products":
[
{
"id":"51",
"op_id":"294",
"name":"Search Marketing",
"order_product_status_id":"1",
"vendor":"Metrix 4 Media",
"price":"200.0000",
"final_price":"600.0000",
"insertions":
{
"package_count":1,
"order_xcid":"",
"business_naics":
"Golf Courses and Country Clubs",
"rev_rec_xcid":"",
"attributes":
{
"products_name":"Search Marketing",
"total_price":"600.00",
"Industry Name":"Arts, Entertainment, and Recreation",
"DFW Regions":"East, North, Northeast, Northwest, South, West, Central",
"Duration":"3 months",
"Campaign Date Range":"May 28, 2010 - August 28, 2010",
"1. Package":"Golf Courses and Country Clubs - 100 clicks at $200.00 per month."
},
"orders_products_id":"294"
}
}
],
"customer":{
"id":"66","name":"Dea Foy",
"company":"User Friendly",
"street_address":"333 N Lenox Ave",
"suburb":"",
"city":"Orlando",
"postcode":"10001",
"state":"18",
"country":
{
"title":"United States"
},
"telephone":"919-555-1212",
"naics_code":null,
"naics_name":null,
"account_number":"",
"email_address":"dmarsh@ahbelo.com"
},
"csr_assigned":
[
{
"user_first_name":"Ben",
"user_last_name":"Portis",
"user_name":"bportis@yahoo.com",
"phone_number":""
}
]
},

{"info":{"orders_id":"303","date_purchased":"2010-06-14 16:59:07","orders_status":"Pending","last_modified":null},"totals":[],"products":[{"id":"54","op_id":"359","name":"Neighborsgo",
"order_product_status_id":"1","vendor":"Wave2 Media Solutions","price":"104.8000","final_price":"1260.0000","insertions":{"112":{
"products_name":"Neighborsgo","total_price":"1,260.00","Business Type":"Small Business Retail","Ad Size":"NGO-1\/8H-BW",
"First Run Date":"07\/02\/2010","Last Run Date":"07\/30\/2010","Zone":"Allen, Frisco\/Little Elm, Irving, Richardson\/Lake Highlands",
"Allen":{"Zone":"Allen","Publication":"NeighborsGo","Status":"Active","Dates":"2010-07-02, 2010-07-16, 2010-07-30","Price":"105.00",
"Impressions":null},"orders_products_id":"359","insertionid":112,"rev_rec_xcid":"12345","sp_id":"0"},"113":{"products_name":
"Neighborsgo","total_price":"1,260.00","Business Type":"Small Business Retail","Ad Size":"NGO-1\/8H-BW","First Run Date":
"07\/02\/2010","Last Run Date":"07\/30\/2010","Zone":"Allen, Frisco\/Little Elm, Irving, Richardson\/Lake Highlands",
"Frisco\/Little Elm":{"Zone":"Frisco\/Little Elm","Publication":"NeighborsGo","Status":"Active","Dates":
"2010-07-02, 2010-07-16, 2010-07-30","Price":"105.00","Impressions":null},"orders_products_id":"359","insertionid":113,"rev_rec_xcid":
"","sp_id":"0"},"114":{"products_name":"Neighborsgo","total_price":"1,260.00","Business Type":"Small Business Retail","Ad Size":
"NGO-1\/8H-BW","First Run Date":"07\/02\/2010","Last Run Date":"07\/30\/2010","Zone":
"Allen, Frisco\/Little Elm, Irving, Richardson\/Lake Highlands","Irving":{"Zone":"Irving","Publication":"NeighborsGo","Status":
"Active","Dates":"2010-07-02, 2010-07-16, 2010-07-30","Price":"105.00","Impressions":null},"orders_products_id":"359","insertionid":
114,"rev_rec_xcid":"","sp_id":"0"},"115":{"products_name":"Neighborsgo","total_price":"1,260.00","Business Type":
"Small Business Retail","Ad Size":"NGO-1\/8H-BW","First Run Date":"07\/02\/2010","Last Run Date":"07\/30\/2010","Zone":
"Allen, Frisco\/Little Elm, Irving, Richardson\/Lake Highlands","Richardson\/Lake Highlands":{"Zone":"Richardson\/Lake Highlands",
"Publication":"NeighborsGo","Status":"Active","Dates":"2010-07-02, 2010-07-16, 2010-07-30","Price":"105.00","Impressions":null},
"orders_products_id":"359","insertionid":115,"rev_rec_xcid":"","sp_id":"0"}}}],"customer":{"id":"54","name":"Thuy
Nolan","company":"","street_address":"8088 Park Ln","suburb":"","city":"Dallas","postcode":"75231","state":"57","country":{"title":
"United States"},"telephone":"444-236-6632","naics_code":null,"naics_name":null,"account_number":"","email_address":
"tnolan@gigawax.com"},"csr_assigned":[{"user_first_name":"Thuy CSR 1","user_last_name":"Nolan CSR 1","user_name":
"ttruman2@ahbelo.com","phone_number":"214-222-3333"},{"user_first_name":"Z","user_last_name":"Trumanx","user_name":
"saulttrumannet@gmail.com","phone_number":"2144972938"}]}]}
Sorry, here is the stack:

HTTP/1.0 200 OK
org.codehaus.jackson.map.JsonMappingException: Unrecognized field "orders_export" (Class com.bim.ssp.dto.OrderForm), not marked as ignorable
at [Source: org.apache.commons.httpclient.AutoCloseInputStream@126e85f; line: 1, column: 2]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:159)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:247)
at org.codehaus.jackson.map.deser.StdDeserializer.reportUnknownProperty(StdDeserializer.java:366)
at org.codehaus.jackson.map.deser.StdDeserializer.handleUnknownProperty(StdDeserializer.java:352)
at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:542)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:401)Binding Error: org.codehaus.jackson.map.JsonMappingException: Unrecognized field "orders_export" (Class com.bim.ssp.dto.OrderForm), not marked as ignorable
at [Source: org.apache.commons.httpclient.AutoCloseInputStream@126e85f; line: 1, column: 2]

at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:286)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1158)
at com.bim.ssp.test.RetrieveSSPOrders.testGetOrderByCustomerId(RetrieveSSPOrders.java:97)
at com.bim.ssp.test.RetrieveSSPOrders.main(RetrieveSSPOrders.java:32)
java.io.IOException: Attempted read on closed stream.
at org.apache.commons.httpclient.AutoCloseInputStream.isReadAllowed(AutoCloseInputStream.java:183)
at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:107)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
Looks good (those @JsonSerialize and @JsonDeserialize annotations are not needed, @JsonProperty implies them, but it doesn't harm). But are you sure you are specifying correct type to bind to? What is the exact mapper.readValue() call you are using?
Hi Tatu,

Thank you for responding!

Maybe that's my problem......Let me take a step back and explain what i'm attempting to do.

I have another web service that i'm contacting using http post due to fire wall restrictions. I'm receiving back a JSON string. From this point i'm a bit confused as to how to map this string to java. I need to be able to convert the JSON string to a java object, then convert this to xml after changing some of the tag names to conform to the system that I will be sending the xml to for consumption.

So my questions are........

How do I convert/map a JSON string with multi dimentional arrays to a Java Object ?
How do I convert a java object to xml?

Examples are greatly welcomed since I have not seem or come across many exmples with Jackson.

Below is an example of the JSON I will be mapping.

Thank you in Advance Tatu!

{"orders_export":
[{
"info":
{
"orders_id":"250",
"date_purchased":"2010-05-18 16:10:50",
"orders_status":"Pending",
"last_modified":null
},
"totals":[],
"products":
[{
"id":"51","op_id":"294",
"name":"Search Marketing",
"order_product_status_id":"1",
"vendor":"Metrix 4 Media",
"price":"200.0000",
"final_price":"600.0000",
"insertions":
{
"package_count":1,
"order_xcid":"",
"business_naics":"Golf Courses and Country Clubs",
"rev_rec_xcid":"",
"attributes":
{
"products_name":"Search Marketing",
"total_price":"600.00",
"Industry_Name":"Arts, Entertainment, and Recreation",
"DFW_Regions":"East, North, Northeast, Northwest, South, West, Central",
"Duration":"3 months",
"Campaign_Date_Range":"May 28, 2010 - August 28, 2010",
"one_Package":"Golf Courses and Country Clubs - 100 clicks at $200.00 per month."
},
"orders_products_id":"294"
}
}],
"customer":
{
"id":"66",
"name":"Dea Foy",
"company":"User Friendly",
"street_address":"333 N Lenox Ave",
"suburb":"",
"city":"Orlando",
"postcode":"10001",
"state":"18",
"country":
{
"title":"United States"
},
"telephone":"919-555-1212",
"naics_code":null,
"naics_name":null,
"account_number":"",
"email_address":"dmarsh@ahbelo.com"
},
"csr_assigned":
[{
"user_first_name":"Ben",
"user_last_name":"Portis",
"user_name":"bportis@yahoo.com",
"phone_number":""
}]
}]
}
Hi Tatu,

To answer your ealier question about mapping, i'm using the following lines:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
OrderForm user = mapper.readValue(new File("C:\\temp\\SampleSSPOrder.txt"), OrderForm.class);
I error out on the first object in the JSON File orders_export which I think i'm not understanding how to define my bean. orders_export is the first object and is an array of export orders. My bean defines it in the following way:
private Vector orders_export = new Vector();

Can you please look at my json.txt file as well as my bean and help me understand how need to map this? All i'm looking for is some help on defining an array and maybe a stand alone object to get me going.

Again, thanks so much for any help you can provide!

DMac
Sorry Tatu.....here is my sample JSON.txt

{"orders_export":[{"info":{"orders_id":"250","date_purchased":"2010-05-18 16:10:50","orders_status":"Pending","last_modified":null},"totals":[],"products":[{"id":"51","op_id":"294","name":"Search Marketing","order_product_status_id":"1","vendor":"Metrix 4 Media","price":"200.0000","final_price":"600.0000","insertions":{"package_count":1,"order_xcid":"","business_naics":"Golf Courses and Country Clubs","rev_rec_xcid":"","attributes":{"products_name":"Search Marketing","total_price":"600.00","IndustryName":"Arts, Entertainment, and Recreation","DFWRegions":"East, North, Northeast, Northwest, South, West, Central","Duration":"3 months","CampaignDateRange":"May 28, 2010 - August 28, 2010","Package":"Golf Courses and Country Clubs - 100 clicks at $200.00 per month."},"orders_products_id":"294"}}],"customer":{"id":"66","name":"Dea Foy","company":"User Friendly","street_address":"333 N Lenox Ave","suburb":"","city":"Orlando","postcode":"10001","state":"18","country":{"title":"United States"},"telephone":"919-555-1212","naics_code":null,"naics_name":null,"account_number":"","email_address":"dmarsh@ahbelo.com"},"csr_assigned":[{"user_first_name":"Ben","user_last_name":"Portis","user_name":"bportis@yahoo.com","phone_number":""}]}]}
Ok that looks ok, since OrdersExport does have property "orders_export" (and getters and setters for it).
So that should be ok -- not sure why you get unrecognized property there.
Mapping of JSON arrays should be as expected, Java type needs to be array or Collection (List, Set).
And JSON objects map to Maps as well as beans with appropriate setters.

Due to sheer size of code and json it is hard to tell for sure; it might be easiest to start building it piece by piece, to see how far binding succeeds. But from sample that you had:

{"orders_export":
[{
"info":
{
"orders_id":"250",
"date_purchased":"2010-05-18 16:10:50",
"orders_status":"Pending",
"last_modified":null
},
"totals":[],
...
}]}

it would seem like bean should look like:
(note: I use public field, but setter/getter pair works the same)

class OrdersExport {
@JsonProperty("orders_export") public List orders;
}
class Order {
public Info info;
public int[] totals; // or whatever type it should have
}

Nothing too unusual. I did not find an obvious problem in your definition, but it's probably just misnaming or missing level.

I agree in that there isn't too much sample code, fasterxml.com wiki is the place where I try to add content.
Thanks Tatu for getting back so quickly on this.

One other question for you. When defining my bean will everything be inside one single bean?

As you wisely suggested, I will start building it over and add to it as I get it working.

Thanks,
DMac
One other question for you. When defining my bean will everything be inside one single bean?

JSON structure and bean structure should be similar, so usually data won't reside within a single bean if you do not want such a structure.

RSS

© 2014   Created by Tatu Saloranta.   Powered by

Badges  |  Report an Issue  |  Terms of Service