Search code examples
c#jsonparsingconverters

Convert object to json string with property name as string value of class


I have the following class structure:

public class JsonModel
{
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
}

And I have an instance of this class as follows:

var entry = new JsonModel { PropertyName = "foo", PropertyValue = "bar" };

I want to convert this to json, but I want it to come out like this:

{
    "foo": "bar"
}

How cant his be done?


Solution

  • assuming that your class has only 2 properties ( name and value) you can use this

    var entry = new JsonModel { PropertyName = "foo", PropertyValue = "bar" };
        
    var json=   GetJson(entry);
     
    public string GetJson(object obj)
    {  
        var prop= obj.GetType().GetProperties();
       
       var prop1=prop[0].GetValue(obj, null).ToString();
       var prop2= prop[1].GetValue(obj, null).ToString();
    
        return "{\n\"" + $"{prop1}\": \"{prop2}" + "\"\n}";
    }
    

    json

    {
     "foo": "bar"
    }
    

    if you wnat to use a serializer, it can be done like this

    public string GetJsonFromParsing(object obj)
    {
        var json=JsonConvert.SerializeObject(obj);
        var properties=JObject.Parse(json).Properties().ToArray();
    
        var prop1 = properties[0].Value;
        var prop2 = properties[1].Value;
    
        return "{\n\"" + $"{prop1}\": \"{prop2}" + "\"\n}";
    }