9

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?

  • 2
    Quick tip: Whenever you need to use angle brackets, you should enclose them in backticks. Otherwise, SFSE will treat it like html and not render the contents. – Derek F May 18 '18 at 15:16
  • I don't suppose that modifying the source of this JSON is an option, is it? – Derek F May 18 '18 at 15:22
  • Not at the source but actually I could do a find and replace on the string in apex. Replace the "coordinates:" for a polygon with "polygonCoordinates:" and then update the class. – Sam Maton May 18 '18 at 15:24
4

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.

  • 1
    Note that a regex would be safer as there may be whitespace between the left hand square braces. Personally instead I would use JSON.deserializeUntyped and build the Apex typed objects myself: instanceof can be used to check the types of values. – Keith C May 18 '18 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.