📅  最后修改于: 2023-12-03 14:43:54.190000             🧑  作者: Mango
LINQ to JSON is a library provided by Newtonsoft.Json to allow for simple parsing, querying, and manipulation of JSON data structures in C#.
To get started with LINQ to JSON in C#, you'll first need to add the Newtonsoft.Json package to your project. You can do this in Visual Studio by using the NuGet Package Manager, or by adding the package to your .csproj file manually.
Once you've installed the package, you can begin using LINQ to JSON in your code. The first step is usually to parse a JSON string into a JObject
or JArray
object, which can be easily queried using LINQ.
string json = @"{
'name': 'John Doe',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'Anytown',
'state': 'CA'
},
'phoneNumbers': [
'555-1234',
'555-5678'
]
}";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["name"]); // Output: John Doe
JArray nums = (JArray)obj["phoneNumbers"];
foreach (var num in nums)
{
Console.WriteLine(num);
}
// Output:
// 555-1234
// 555-5678
As you can see, parsing a JSON string into a JObject
or JArray
is very simple with LINQ to JSON. Once you have your data structure, you can use LINQ queries to navigate and modify it easily.
JObject obj = JObject.Parse(json);
var addresses = from p in obj.Properties()
where p.Name == "address"
select p.Value;
foreach (var addr in addresses)
{
Console.WriteLine(addr["state"]);
}
// Output: CA
obj["name"] = "Jane Doe";
Console.WriteLine(obj.ToString());
// Output:
// {
// "name": "Jane Doe",
// "age": 30,
// "address": {
// "street": "123 Main St",
// "city": "Anytown",
// "state": "CA"
// },
// "phoneNumbers": [
// "555-1234",
// "555-5678"
// ]
// }
In this example, we use a LINQ query to retrieve the address
object from our JObject
. We then modify the value of the name
property and output the updated JSON string.
LINQ to JSON provides a convenient and powerful way to work with JSON data in C#. Its simple API and use of LINQ make it a great choice for many data querying and manipulation tasks.