[SalesForce] How to deserialize JSON to a class where the same variable name has different data types

I am trying to deserialize some JSON to a class using JSON.deserialize.
My JSON looks like this

{
    "type": "GeometryCollection",
    "geometries": [
        {
            "type": "Point",
            "coordinates": [-3.529138029308078, 50.71957856160531]
        }, 
        {
            "type": "Polygon",
            "coordinates": [
                [
                    [-3.5381984710693364, 50.72477461305143],
                    [-3.5381984710693364, 50.727165282893836],
                    [-3.5295295715332036, 50.727165282893836],
                    [-3.5295295715332036, 50.72477461305143],
                    [-3.5381984710693364, 50.72477461305143]
                ]
            ]
        }
    ]
}

and the class I am trying to use looks like this

public class geometryCollection 
{
  String type;   
  List<geometry> geometries; 
}

public class geometry 
{
  String type;
  /*List<Decimal> coordinates;
  List<List<List<Decimal>>> coordinates;*/
}

As you can see in my JSON the items in the 'geometries' array have a type and coordinates. The problem is that for a point the coordinates are of type List<Decimal> and for polygon they are of type List<List<List<Decimal>>>.

Is there a good way to deserialize this JSON when two different data types use the same name?

Best Answer

So I decided the easiest way is to do a find and replace on the JSON string and change the names of one of the duplicate variables.

String s2 = geoJSON.replace('"coordinates":[[[', '"polygonCoordinates":[[[');

Then I updated my classes to look like this

public class geometryCollection
{
   String type;   
   List<geometry> geometries; 
}

public class geometry
{
   String type;
   List<Decimal> coordinates;
   List<List<List<Decimal>>> polygonCoordinates;
}

Then once I have serialized the JOSN I can change it back.

Related Topic