I'm doing a web service call, and parsing the json response into a wrapper object for display on a Visualforce page.
My wrapper object looks like:
public class CustomerAddresses {
public String line1 {get; set;}
public String line2 {get; set;}
public String city {get; set;}
public String state {get; set;}
}
My json parser looks like:
String fieldName = parser.getCurrentName();
if(fieldName == 'addr' && parser.getCurrentToken() == JsonToken.START_ARRAY){
while(parser.nextToken()!= JsonToken.END_ARRAY){
if(parser.getCurrentToken()==JSONToken.START_OBJECT){
CustomerAddresses s = (CustomerAddresses)parser.readValueAs(CustomerAddresses.class);
customerAddressList.add(s);
}
}
}
and the json file looks something like:
{
"theresponse":{
"addrs":{
"addr":[
{
"line1":"11562 TEST DR",
"line2":"ORANGEVILLE",
"city":"GARDEN GROVE",
"state":"AZ"
},
{
"line1":"123 TEST BLVD",
"line2":"TREE HARBOR",
"city":"FAIRMONT",
"state":"CA"
}
]
},
Here's my problem, if (in the future) someone adds another attribute to the json file, such as "zip" (see example below), then my class breaks because I can't create an object without the attribute being declared in the CustomerAddresses class. How can I ignore json attributes that aren't in my class CustomerAddresses?
Thank you in advance for any help with this!!
Ex: bad json file:
{
"theresponse":{
"addrs":{
"addr":[
{
"line1":"11562 TEST DR",
"line2":"ORANGEVILLE",
"city":"GARDEN GROVE",
"state":"AZ",
"zip":"80001"
},
Best Answer
The documentation for readValueAs says (emphasis mine):
My reading of this is that your code should continue to work when extra JSON attributes are added. But I suggest you create a test case to ensure that the code does what the documentation says.