Find your content:

Search form

You are here

Giving new field names in wrapper classes for JSON deserializing

 
Share

Here is the JSON structure:

{
    "public_index": [
        {
            "index": "wiki_eng",
            "type": "content"
        },
        {
            "index": "wiki_fra",
            "type": "content"
        }
    ],
    "index": [
        {
            "index": "test",
            "flavor": "standard",
            "type": "content",
            "date_created": "Thu May 08 2014 08:17:53 GMT+0000 (UTC)",
            "num_components": 1
        }
    ]
 }

These are the wrapper classes:

    public class ListIndexResponse {
        public List<PublicIndex> publicIndexList;
        public List<Index> indexList;
    }

    public class PublicIndex {
        public String index;
        public String type;
    }

    public class Index {
        public String index;
        public String flavor;
        public String type;
        public String date_created;
        public Integer num_components;
    }

To deserialize the json I used this:

ListIndexResponse response = (ListIndexResponse)JSON.deserialize(res.getBody(), ListIndexResponse.class);
System.debug(JSON.serialize(response));

and the debug output is just:

{"publicIndexList":null,"indexList":null}

changing field names to public_index and index in wrapper class ListIndexResponse worked for me. but is there a way I can specify my own field name, maybe by overriding the constructor ?


Attribution to: vishesh

Possible Suggestion/Solution #1

I believe the JSON.deserialize method matches the JSON content to your Apex class. your names will need to match in order to have this work correctly. If you need to specify your own names, you could create those elements as well, and then relate them together. Something like this:

public List<PublicIndex> getpublicIndexList(){
     return public_index;
}

Attribution to: JimRae
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34681

My Block Status

My Block Content