Skip to content Skip to sidebar Skip to footer

Json Value Is Sometimes A String And Sometimes An Object

I have some JSON that can come in two different formats. Sometimes the location value is a string, and sometimes it is an object. This is a sample of the first format: { 'resul

Solution 1:

To solve this problem you'll need to make a custom JavaScriptConverter class and register it with the serializer. The serializer will load the result data into a Dictionary<string, object>, then hand off to the converter, where you can inspect the contents and convert it into a usable object. In short, this will allow you to use your second set of classes for both JSON formats.

Here is the code for the converter:

classResultConverter : JavaScriptConverter
{
    publicoverride IEnumerable<Type> SupportedTypes
    {
        get { returnnew List<Type> { typeof(Result) }; }
    }

    publicoverrideobjectDeserialize(IDictionary<string, object> dict, Type type, JavaScriptSerializer serializer)
    {
        Result result = new Result();
        result.upon_approval = GetValue<string>(dict, "upon_approval");
        var locDict = GetValue<IDictionary<string, object>>(dict, "location");
        if (locDict != null)
        {
            Location loc = new Location();
            loc.display_value = GetValue<string>(locDict, "display_value");
            loc.link = GetValue<string>(locDict, "link");
            result.location = loc;
        }
        result.expected_start = GetValue<string>(dict, "expected_start");
        return result;
    }

    private T GetValue<T>(IDictionary<string, object> dict, string key)
    {
        objectvalue = null;
        dict.TryGetValue(key, outvalue);
        returnvalue != null && typeof(T).IsAssignableFrom(value.GetType()) ? (T)value : default(T);
    }

    publicoverride IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        thrownew NotImplementedException();
    }
}

Then use it like this:

varser=newJavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
ser.RegisterConverters(newList<JavaScriptConverter> { newResultConverter() });
RootObjectro= serializer.Deserialize<RootObject>(responseValue);

Here is a short demo:

classProgram
{
    staticvoidMain(string[] args)
    {
        string json = @"
        {
          ""result"": [
            {
              ""upon_approval"": ""Proceed to Next Task"",
              ""location"": {
                ""display_value"": ""Corp-HQR"",
                ""link"": ""https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090""
              },
              ""expected_start"": """"
            }
          ]
        }";

        DeserializeAndDump(json);
        Console.WriteLine(newstring('-', 40));

        json = @"
        {
          ""result"": [
            {
              ""upon_approval"": ""Proceed to Next Task"",
              ""location"": """",
              ""expected_start"": """"
            }
          ]
        }";

        DeserializeAndDump(json);

    }

    privatestaticvoidDeserializeAndDump(string json)
    {
        var serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
        RootObject obj = serializer.Deserialize<RootObject>(json);

        foreach (var result in obj.result)
        {
            Console.WriteLine("upon_approval: " + result.upon_approval);
            if (result.location != null)
            {
                Console.WriteLine("location display_value: " + result.location.display_value);
                Console.WriteLine("location link: " + result.location.link);
            }
            else
                Console.WriteLine("(no location)");
        }
    }
}

publicclassRootObject
{
    public List<Result> result { get; set; }
}

publicclassResult
{
    publicstring upon_approval { get; set; }
    public Location location { get; set; }
    publicstring expected_start { get; set; }
}

publicclassLocation
{
    publicstring display_value { get; set; }
    publicstring link { get; set; }
}

Output:

upon_approval:ProceedtoNextTasklocation display_value:Corp-HQRlocation link:https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090----------------------------------------upon_approval:ProceedtoNextTask(nolocation)

Post a Comment for "Json Value Is Sometimes A String And Sometimes An Object"