I have a C# dictionary list as follows:
"additionalDataList": [
{
"key": "notes",
"value": "haasdas\n\ns"
},
{
"key": "twigTemplateId",
"value": "2"
},
{
"key": "AssignedUser",
"value": {
"Name": "To, To",
"Id": 108
}
},
{
"key": "assignedUserId",
"value": "114"
}
],
But, I need to convert this like:
"additionalDataList":
{
"notes": "haasdas\n\ns"
},
{
"twigTemplateId": "2"
},
{
"AssignedUser": {
"Name": "To, To",
"Id": 108
}
},
{
"assignedUserId": "114"
}
How can I get the expected result? I tried to convert in List Object, but did not work.
Update: Code that I have:
public List<KeyValuePair<string, object>> AdditionalDataList { get; set; }
public string AdditionalData {
get
{
return _additionalData;
}
set
{ if (!(value is null))
{
AdditionalDataList = ParseJson(value).ToList();
}
_additionalData = value;
}
}
public Dictionary<string, object> ParseJson(string json)
{
var dict = new Dictionary<string, object>();
if (json is null)
{
return dict;
}
var obj = JObject.Parse(json);
foreach (var property in obj)
{
var name = property.Key;
var value = property.Value;
if (value is JArray)
{
dict.Add(name, value.ToArray());
}
else if (value is JValue)
{
dict.Add(name, value.ToString());
}
else if (value is JObject)
{
dict.Add(name, JObject.Parse(value.ToString()));
}
else
{
throw new NotSupportedException("Invalid JSON token type.");
}
}
return dict;
}
I need to convert the following JSON String: (This is already in Additional Data)
{"notes":"haasdas\n\ns","twigTemplateId":2,"AssignedUser":{"Name":"To, To","Id":108},"assignedUserId":114}
CodePudding user response:
Type List<KeyValuePair<string, object>>
for your property AdditionalDataList
does not represent your desired json. Common convention is to serialize Dictionary
to json object with keys used as names (and not a collection of KeyValuePair
, cause as per standard names should be unique):
public Dictionary<string, object> AdditionalDataList { get; set; }