Deserialize json to list of KeyValue pairs [duplicate] - c#

This question already has answers here:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
(22 answers)
Closed 4 years ago.
I have the following json:
[
{
"key":"key1",
"value":"val1"
},
{
"key":"key2",
"value":"val2"
}
]
How can I deserialize it into an list/array of NameValuePair<string, string>?
Example:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<List<KeyValuePair<string,string>>>(json);
The above code runs but the data inside the list is null. I can extract the array into an List<Object> though.

First off, you should not be using JavaScriptSerializer, Microsoft even explicitly says that in the JavaScriptSerializer docs.
To deserialize an object in Json.NET the syntax is very similar:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var result = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);
Fiddle here
UPDATE
If you are using .NET Core 3 / .NET 5 or .NET 6, the System.Text.Json library is included without an additional dependency.
The syntax for deserializing with that library is:
var result = JsonSerializer.Deserialize<List<KeyValuePair<string,string>>>(jsonString);

Related

How to delete and update based on a path in System.Text.Json (.NET 6)?

I have a JSON text:
{
"a":[
{
"a1":"string",
"a2":"string",
"a3":"string"
}
],
"b":"2021-12-29T14:20:21.948Z",
"c":{
"c1":[
{
"c11":"string",
"c12":"string",
"c13":"string",
"c14":true,
"c15":true,
"c16":"2021-12-29T14:20:21.948Z",
"c17":"string"
}
]
}
}
JsonNode class always has a unique path I want to use them to find a specific value (update/delete them).
So, I want to use System.Text.Json and .NET 6 to have the following methods:
public static JsonNode UpdateValue(string json /*JsonNode json*/, string path, object value)
{
// ?
}
public static JsonNode RemovePath(string json /*JsonNode json*/, string path)
{
// ?
}
Is it possible?
In short: Unfortunately you can't
Modification
JsonDocument is readonly by design. Before JsonNode has been introduced you had to
deserialize it as Dictionary<string, object>
perform the modification
serialize it back to json
Since JsonNode has been introduced in .NET 6 you can do the following
var node = JsonNode.Parse(json);
var rootObject = node as JsonObject;
var aArray = rootObject["a"] as JsonArray;
var firstA = aArray[0];
firstA["a3"] = "modified";
or in short
var node = JsonNode.Parse(json);
node["a"][0]["a3"] = "modified";
Locate element by Path
Even though the need has been expressed in 2019 it hasn't been address yet. But as layomia said
This feature is proposed for .NET 6, but not committed. To be clear, we acknowledge that this is an important feature for many users, however, work on features with higher priority may prevent this from coming in .NET 6.
Unfortunately this feature did not make it to the .NET 6.
There are 3rd party libraries which offers this capability for JsonDocument. One of the most mature one is called JsonDocumentPath. With its SelectElement method you can really easily retrieve the given field as JsonElement
var doc = JsonDocument.Parse(json);
JsonElement? a3 = doc.RootElement.SelectElement("$.a[0].a3");
Interoperability
Even though there is a way to convert JsonElement to JsonNode and in the other way around:
var a3Node = JsonSerializer.Deserialize<JsonNode>(a3.Value);
a3Node = "a";
it does not really help since the a3Node represents only the a3 field and according to my understanding you can't just merge two JsonNodes.
update json using Newtonsoft.Json
string json = File.ReadAllText("json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["a"][0]["test1"] = "new values";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

Deserialiazing Json dictionary to list [duplicate]

This question already has answers here:
How can I deserialize a child object with dynamic (numeric) key names?
(2 answers)
Closed 4 years ago.
I have a Json file, with the object serialized correctly, but the problem is that the json has what seems like a dictionary with keys that are strings "0","1" and so on.
Is there any way, not involving writing an own parser, to correctly deserialise these into a list?
"WeaponSlots":{
"0":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
},
"1":{
"WeaponInstalled":null,
"AllowedWeaponTypes":{
"0":{
"0":2
}
},
"AllowedWeapons":null
}
Example file: https://pastebin.com/i3LQ3L7j
You can use the datatype Dictionary<string, object> to deserialize this..
static void Main(string[] args)
{
// load the file.
var file = File.ReadAllText("Example.json");
// to generate the 'Example' classes from JSON I used
// https://app.quicktype.io and changed the name to 'Example'
var example = JsonConvert.DeserializeObject<Example>(file);
// select the value of each dictionary entry into a list.
var sections = example.Sections.Select(x => x.Value).ToList();
}

Parsing complicated Json Array in C# [duplicate]

This question already has an answer here:
Parse JSON string with inconsistent field names
(1 answer)
Closed 7 years ago.
I have a json array:
{
"array":[
{
"Name_0":"Value_0",
"Name_1":"Value_1"
},
{
"Name_2":"Value_2",
"Name_3":"Value_3",
"Name_4":"Value_4",
"Name_5":"Value_5"
}
]
}
The data structures inside the json array are not consistent.
How can I parse them in C#?
Thanks!
One way to do this will be
var serializer = new JavaScriptSerializer();
var data = serializer
.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(input);
This is because your json data structure is like this. For innermost element we have a Dictionary<string, string> which is nested in a generic list which in turn is nested in another generic dictionary.

C# remove json child node using newtonsoft

I am developing an app using c# wpf in .net 3.5.
I use newtonsoft library to parse the json string.
I want to know how to remove a child node of json.
For example,
My json data =
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}]}
The function
jobject.Remove("employees");
removes all the nodes sucessfully
I would like to know how to remove the first employee detail alone.
Once you parse your json into a JObject, the employees property will be a JArray. The JArray class has methods you're looking for, such as JArray.RemoveAt
The following code will do what you want
string json =
#"{
""employees"":[
{ ""firstName"":""John"", ""lastName"":""Doe""},
{ ""firstName"":""Anna"", ""lastName"":""Smith""},
{ ""firstName"":""Peter"", ""lastName"":""Jones""}
]
}";
dynamic obj = JObject.Parse(json);
(obj.employees as JArray).RemoveAt(0);
// obj now only has "Anna Smith" and "Peter Jones"
dynamic was introduced in .NET 4.0, so for 3.5 you'd use something like this instead
JObject obj = JObject.Parse(json);
(obj["employees"] as JArray).RemoveAt(0);
obj.SelectToken("Employees")[0].Parent.Remove();

c# - deserialization of specific JSON

I have JSON text with structure like this:
{
"324523":{"a":1345, "b":2344},
"134565":{"a":1642, "b":2322},
"123426":{"a":1556, "b":2674},
...
}
Is it possible to make .NET classes to deserialize such JSON? It looks like a Dictionary, but DataContractJsonSerializer doesn't deserialize this.
Try JSON.Net, which you can obtain from NuGet, or from the JSON.Net website.
Deserializing:
var jsonValues = JsonConvert.DeserializeObject(someJsonString);
var pocoValue = JsonConvert.DeserializeObject<YourClass>(someJsonString);
// or as a dictionary:
var dictionary = JsonConvert.DeserializeObject<Dictionary<MyClass>>(someJsonString);

Categories