Search code examples
c#jsondeserializationjson-deserializationjsonconvert

Deserialize the Json property(Nested Json) as string in C#


I need requirement that the deserialize the json as string which is available inside another Json. I have the Json string as like below,

string testJson =
   "{
        "AssemblyName":"AssemplyName",
        "ClassName":"AssemplyName.ClassName",
        "Options":"{ "property1":"value1","property2":10}"
   }";

To deserialize, I have the class like below,

public class CType
{
    public string AssemblyName { get; set; }
    public string ClassName { get; set; }
    public string Options { get; set; }
}

So, I deserialize like below,

CType cType = JsonConvert.DeserializeObject<CType>(testJson);

Now, I expect the resuly like below,

AssemblyName = "AssemplyName"
ClassName = "AssemplyName.ClassName"
Options = "{ "property1":"value1","property2":10}"

It would be much appreciated anyone can help on this


Solution

  • You can declare the class like this.

    public class Options
    {
        public string property1 { get; set; }
        public string value1 { get; set; }
        public int property2 { get; set; }
    }
    
    public class Example
    {
        public string AssemblyName { get; set; }
        public string ClassName { get; set; }
        public Options Options { get; set; }
    }
    

    Then you caan deserialize and serilize the string like this.

    string str = "json string";
    Example cType = JsonConvert.DeserializeObject<Example>(str);
    string json = JsonConvert.SerializeObject(cType.Options);
    

    Valid Json:

    {
        "AssemblyName": "AssemplyName",
        "ClassName": "AssemplyName.ClassName",
        "Options": {
            "property1 ": "",
            "value1": "",
            "property2": 10
        }
    }
    

    For dynamic nested json you can declare the Options as dictionary. Above code will work.

    public Dictionary<string, string> Options { get; set; }