codiaak
codiaak

Reputation: 1540

Gson - Conditional JSON Deserialization (Sanity Checks)

I have code in my android project that correctly deserializes json into POJO's using gson. I wish to add some condtional acceptance checks (sanity checks) to the incoming json. For instance, with the data structure below, I wish for the gson parser to only add objects where the start date < end date. I know I could iterate through the list after it is populated to remove invalid items, but I was wondering if there was any way to reject the items on the fly. Any help would be appreciated.

Example JSON

{
  "Items" : [
     {
        "Name" : "Example Name",
        "Start" : "2010-10-16 10:00:00",
        "End" : "2011-03-20 17:00:00",
        <other fields>
    }, 
    <several more items>
  ]
}

ItemList.java

public class ItemList {
    private List<ItemHeader> Items;

    public void setItemHeaders(List<ItemHeader> headers) {
        Items = headers;
    }

    public List<ItemHeader> getItemHeaders() {
        return Items;
    }
}

ItemHeader.java has fields for name, start, end and all the other fields.

Upvotes: 1

Views: 1559

Answers (1)

Brian Roach
Brian Roach

Reputation: 76908

You'd need to write your own deserializer and have it throw an exception when your condition isn't met.

http://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer

I don't know that you should do this, but it's possible.

Upvotes: 2

Related Questions