Home > Back-end >  C# convert object to json string with property name as string value of class
C# convert object to json string with property name as string value of class

Time:12-29

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"
}

Anyone know how I can do this? I am sure it must be quite simple?

CodePudding user response:

If you use Newtonsoft Json.NET you can use a JsonConverter implementation to handle it.

Here's a rather naive implementation:

public class JsonModelConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) => objectType == typeof(JsonModel);

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        var dict = serializer.Deserialize<Dictionary<string, string>>(reader);
        var item = dict.First();
        return new JsonModel { PropertyName = item.Key, PropertyValue = item.Value };
    }

    public override void WriteJson(JsonWriter writer, object value,
        JsonSerializer serializer)
    {
        var model = (JsonModel)value;
        var dict = new Dictionary<string, string>();
        dict[model.PropertyName] = model.PropertyValue;
        serializer.Serialize(writer, dict);
    }
}

You have to pass this in to the SerializeObject and DeserializeObject<T> methods, here's a usage example with example output:

void Main()
{
    var t = new Test
    {
        Model = new JsonModel { PropertyName = "key", PropertyValue = "some value" }
    };
    string json = JsonConvert.SerializeObject(t, new JsonModelConverter());
    Console.WriteLine(json);

    var t2 = JsonConvert.DeserializeObject<Test>(json, new JsonModelConverter());
    Console.WriteLine($"{t2.Model.PropertyName}: {t2.Model.PropertyValue}");
}

public class Test
{
    public JsonModel Model { get; set; }
}

Output:

{"Model":{"key":"some value"}}
key: some value

CodePudding user response:

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}";
}

CodePudding user response:

in most programming languages, including C#, the common way to serialize to JSON would be to take the field's name as the key name, and the field's value as the value.

what you're asking to achieve is to somehow couple between two different fields, which is not a common thing to do.

CodePudding user response:

To output key value pairs, just specify what the key and value is in an interface. In your case:

public interface IKVP
{
    string PropertyName { get; set; }
    string PropertyValue { get; set; }
}

Then you can output any class that adheres to the interface:

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

Once that is done, create an extension method which will only take classes that implement the interface:

public static class ClassConverter
{
    public static string ToJson<T>(this T value)  where T : IKVP
      => $"{{ \x22{value.PropertyName}\x22 : \x22{value.PropertyValue}\x22  }}";

}

Once done, output the json string:

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

var json = entry.ToJson(); // { "foo" : "bar"  }

Build upon this as needed for more complex situations.

  • Related