1

Right now I have something like global static String readJson(String abc) { return abc;} and when I POST a json {'abc':'success'}, it returns the string success.

Now if I have something with multiple levels of structure like:

{
  "parking_spot": {
    "0": {
    "car": "car",
    "color": "color",
    "location_data": {
        "0": {
        "location": "building, level, spot",
        "time_parked": "time"
        }
    }
    }
}

I have two questions now:

1.) How would I set up the method parameters and deserialize it to read this?

2.) Is there any way to deal with reading and deserializing JSON given that I don't know the structure of the json in advance?

Thanks!

1 Answer 1

5

The JSON.deserialize method can deserialize into a tree of objects providing the names used in the JSON are legal identifier names in Apex. And json2apex is an easy way to generate the Apex classes. But your JSON has the name "0" in it so that approach will not work.

Instead you will have to use JSON.deseializeUntyped and the documentation for that illustrates how to walk down through the levels of structure.

If you don't know the structure in advance, then you will need to iterate over the map keys and use a series of instanceof checks for each Object to decide whether you have reached a string/number/boolean/null and so are finished or will need to walk down into a further object or array.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .