Home > Software design >  C# | Create a json string out of static class fields with values
C# | Create a json string out of static class fields with values

Time:02-12

I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \""   prop.Name   "\" is not found in class... skip");
        }
    }

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s. Key value pairs saved in string, could be wrapped at the end like

    ResultString = "{ "   resultString   " }";

C# .NET 4.7.2 (console app)

CodePudding user response:

As others have said, a static class is not a good design here.

However, it is possible to map it back to JSON with some simple reflection:

public static JObject MapStaticClassToJson(Type staticClassToMap)
{
    var result = new JObject();
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    {
        result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
    }
    
    return result;
}

CodePudding user response:

I think it would be nice to have some simple code to assign json properties to a static class properties too. I created this code using @RichardDeeming answer

public static void MapStaticClassFromJson(string json, Type staticClassToMap)
{
    var jsonObject = JObject.Parse(json);
        
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    prop.SetValue(null, Convert.ChangeType(jsonObject[prop.Name], prop.PropertyType, CultureInfo.CurrentCulture), null);
}

test

 MapStaticClassFromJson(json,typeof(Data));
 Console.WriteLine(Data.StaticPropertyName_int); 
 Console.WriteLine(Data.StaticPropertyName_string);

result

34
string_value_of_this_property
  • Related