Ninita Ninita - 6 months ago 28
C# Question

Convert JS object with a list to C# list

My client is sending me a object like this:

"content": {
"title": "data title",
"values": {
"25": "some description",
"26": "some info",
"27": "some text",
"28": "some other data",
"29": "more info",
"30": "more text",
"31": "and another more description"
}
}


and I need to save the
values
on a C#
List<>
object.
I'm trying to get and save those values like this:

public static List<MyKeyValuePair> GetClientValues(dynamic content)
{
var myList = new List<MyKeyValuePair>();

try
{
foreach (PropertyInfo pi in content.values.GetType().GetProperties())
{
var value = "";
myList.Add(new MyKeyValuePair() { Id = int.Parse(pi.Name), Description = pi.GetValue(value, null).ToString() });
}
}
catch { }

return myList;
}


However on the
foreach
line I'm getting this error message:


'System.Collections.Generic.Dictionary.values' is
inaccessible due to its protection level


How can I solve this?

Answer Source

If the dynamic is already typed, you should be able to do the following:

public static List<MyKeyValuePair> GetClientValues(dynamic content)
{
    var myList = new List<MyKeyValuePair>();

    foreach (var kv in content["values"])
    {
        myList.Add(new MyKeyValuePair {
            Id = int.Parse(kv.Key),
            Description = kv.Value
        });
    }

    return myList;
}

Otherwise, you may need to deserialize the input json string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download