1

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @styfle! With that code I was getting the same error message as well but I change my foreach line to foreach (var kv in content["values"]) and now it works perfectly. Thank you very much
0

If you are using visual studio 2013 and greater you copy this json and generate a class out of it using the paste json as class under the edit menu, however if you are using a lower version of VS you can still type out the class structure and then the next step would be to use newtonsoft json to deserialise json into the class created above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.