0

Hi I have a Json body that can either send over a list vs a string. Right now I have it set to just capture a string "type"

public class PackageInformation{
      public String location {get;set;}
      pubic string type {get;set;}
      public string name [get;set;}

but sometimes the json body comes over as a list of "type" which I would need to create an object for it like this:

public class PackageInformation{
      public String location {get;set;}
      pubic List<type> types {get;set;}
      public string name [get;set;}

How can I write my class to parse my json body if it comes either as a string or a list?

2

In the situation where your incoming JSON uses different names for the String and List<String> varieties, you don't need to do much of anything at all.

Simply including both the String type and List<String> types variables in your PackageInformation class, and using JSON.deserialize(<JSON here>, PackageInformation.class) will work because the regular deserialize() method doesn't care about extra data, nor missing data.

If you need to use JSON.deserializeStrict(), or if your incoming JSON uses a single name (like "type") for both a List<String> and a String value, then there isn't much you can do to avoid requiring two different deserialization classes.

You'd also need to be able to determine which deserialization class you'd need to use.

Using exceptions for this (i.e. try one class, catch the JSON exception if one occurs, then try the other class) is not recommended. This is known as the "exceptions as flow control" antipattern.

Instead, I think the best option available to us at this time is to first use deserializeUntyped() and test whether your target variable is an instance of List<Object> or not.

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.