Jackson json mapper example: unrecognized field 

Joined:
08/13/2009
Posts:
172

February 27, 2012 12:19:19    Last update: February 27, 2012 12:19:19
Mapping Java objects to Jackson JSON is pretty simple. But if you name a JSON field wrong, you'll get the "Unrecognized field ... (Class ...), not marked as ignorable" error. The rule for mapping a Java bean attribute name to a JSON field name is: lower all leading capital letters until the first lower case letter.

For example, this Java class:
package com.example;

public class Person {
    private String firstName;
    private String lastName;
    private String SSN;
    private String mobilePhone;

    public String getFirstName() {
	return this.firstName;
    }

    public void setFirstName(String firstName) {
	this.firstName = firstName;
    }

    public String getLastName() {
	return this.lastName;
    }

    public void setLastName(String lastName) {
	this.lastName = lastName;
    }

    public String getSSN() {
	return this.SSN;
    }

    public void setSSN(String SSN) {
	this.SSN = SSN;
    }

    public String getMOBilePHone() {
	return this.mobilePhone;
    }

    public void setMOBilePHone(String mobilePhone) {
	this.mobilePhone = mobilePhone;
    }

}

maps to this JSON string:
{
    "firstName": "Jane",
    "lastName": "Doe",
    "ssn": "999-99-9999",
    "mobilePHone": "222-22-2222"
}

Test code:
package com.example;

import java.net.URL;

import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;

import org.codehaus.jackson.map.ObjectMapper;

public class TestApp {
    private Person p;

    @Before
    public void setUp() throws Exception {
	URL url = TestApp.class.getClassLoader().getResource("person.json");
	ObjectMapper mapper = new ObjectMapper();
	p = mapper.readValue(url, Person.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void validatePerson() {
	assertEquals(p.getFirstName(), "Jane");
	assertEquals(p.getLastName(), "Doe");
	assertEquals(p.getSSN(), "999-99-9999");
    }
}
Share |
| Comment  | Tags