skip to Main Content

I have a C# class like the following:

public class Test
{
    public string x;
    public int y; 

    public string str1;
    public string str2;
    ... 
    ...
    public string strN;
}

with N that could be 0 or greater. That means that there could be 0 or N > 0 string properties strX.
So the problem is that I do not know at build time how many strings strX there will be and I need to serialize a complex structure that contains instances of the class Test. I need to serialize/deserialize objects that could have a variable number of properties strX at run time and I cannot use an array, because they must be separate member properties and not members of a collection.

Any helpful hint would much appreciated.

2

Answers


  1. I’m afraid you want to have a similar feature like what we can do in JS to read json content directly without having a model binding to the json data. If so, then I had a test with code below which might meet your requirement.

        public void readJsonString() { 
            string json1 = "{"x":"valuex", "y":2, "str1":"value1"}";
            string json2 = "{"x":"valuex", "y":2, "str1":"value1", "str2":"value2", "str3":"value3"}";
            JObject jsonObj1 = JObject.Parse(json1);
            JObject jsonObj2 = JObject.Parse(json2);
            var a = jsonObj1.ContainsKey("str2") ? jsonObj1["str2"] : "null";
            var b = jsonObj2.ContainsKey("str2") ? jsonObj2["str2"] : "null";
        }
    

    enter image description here

    In addition, I don’t think it’s a good idea to handle data like this. It’s not good for maintance at least… It’s better for us to parse data format at first then create a model for it.

    Login or Signup to reply.
  2. I’m not sure I understand the problem well but you could use the method GetFields()
    https://learn.microsoft.com/en-us/dotnet/api/system.type.getfields?view=net-8.0

    you should be able to easily get the desired result with something like this:

    Type myType = typeof(Test);
    FieldInfo[] myField = myType.GetFields();
    //myField.length <= this could  be what you are looking for
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search