Daniel
Daniel

Reputation: 7724

Deserialize json object as a string

I have a class A that has a field string data.

I perform a server request that gets me a json text that I convert to A:

var a = JsonConvert.DeserializeObject<A>(jsonResponse);

The problem is sometimes data comes as a string (e.g: Ball) and sometimes it comes as a json object, like this:

"data" : {
    "field1" : "Ball",
    "field2" : "Foo"
}

And this breaks the deserialization, since the field data was expecting a string.

Is there a way to capture data from the json text as a string even if it comes as a json object?

Upvotes: 0

Views: 66

Answers (2)

Nitin S
Nitin S

Reputation: 7601

You can deserialize your json into dynamic object instead of concrete class

dynamic objX = JsonConvert.DeserializeObject<ExpandoObject>(Test2);

How about declaring two separate DTO classes, when it is string deserialize to B, if it is json object deserialize to A

using System;
using Newtonsoft.Json;
using System.Dynamic;

public class A
{
    public Data data{get;set;}
}

public class B
{
    public string data{get;set;}
}

public class Data
{
    public string field1{get;set;}
    public string field2{get;set;}
}

public class Program
{
    public static void Main()
    {
        string Test1 = "{\"data\":\"strTest\"}";
        string Test2 = "{\"data\":{\"field1\":\"strTest1\", \"field2\":\"strTest2\"}}";
        //var obj1 = JsonConvert.DeserializeObject<A>(Test1);//fails
        //obj1.Dump();
        //var obj2 = JsonConvert.DeserializeObject<A>(Test2);
        //obj2.Dump();
        dynamic objX = JsonConvert.DeserializeObject<ExpandoObject>(Test2);//try switching Test1
        if(objX.data.GetType()==typeof(string))
        {
            //its a string  
            var obj1 = JsonConvert.DeserializeObject<B>(Test1);//fails
            obj1.Dump();
        }
        else
        {
            //its a json object
            var obj2 = JsonConvert.DeserializeObject<A>(Test2);
            obj2.Dump();
        }
    }
}

fiddle here https://dotnetfiddle.net/EJkdMW

Upvotes: 0

Siavash Mortazavi
Siavash Mortazavi

Reputation: 1862

How about something like this as a starting point? (inspired by .NET TryParse methods):

public static bool TryDeserialize<T>(string jsonString, out T result)
{
    try
    {
        result = JsonConvert.DeserializeObject<T>(jsonString)!;
        return result is not null;
    }
    catch
    {
        result = default!;
        return false;
    }
}

Then you can use it like:

if (TryDeserialize<YourObjectModel>(jsonString, out YourObjectModel result))
{
    Console.WriteLine($"result is {result.Field1}");
}
else
{
    Console.WriteLine($"{nameof(jsonString)} value is {jsonString}");
}

Upvotes: 2

Related Questions