Creating JProperty from Dictionary with LINQ in JSON.NET
I need to get JSON
{
"question":"q1",
"answ开发者_开发技巧ers": {
1:"ans1",
2:"ans2",
3:"ans3"
}
"corr":[1,2]
}
with this expression contains LINQ
JObject jsonContent =
new JObject(
new JProperty("question", _question),
new JProperty("answers",
new JObject(
from ans in _answers
select new JProperty (ans.Key.ToString(),ans.Value))),
new JProperty("corr",
new JArray(
from ans in _correctAnswers
select ans)));
where
string _question;
List<int> _correctAnswers;
Dictionary<int, string> _answers;
I have a problem with converting Dictionary into JProperty
System.ArgumentNullException: Value cannot be null.
Parameter name: source
UPD: The all of values are set. There is no null answer
UPD2: Sorry. All works fine. The problem was in db-access layer
Looks like there might be a answer in the Dictionary that is null
try:
select new JProperty (ans.Key.ToString(),ans.Value ?? string.Empty)
To convert a dictionary to JProperty I serialize and parse it again:
var dict = new Dictionary<string, string>();
// add items
var prop = new JProperty("yourprop", JObject.Parse(JsonConvert.SerializeObject(dict.Values)));
I Hope it could be of any help.
精彩评论