C# 按路径设置JSON属性
有没有办法使用Json.NET通过路径设置属性C# 按路径设置JSON属性,c#,json,json.net,C#,Json,Json.net,有没有办法使用Json.NET通过路径设置属性 JObject o = JObject.Parse(@"{ 'CPU': 'Intel', 'Drivers': { 'Mouse': 'HPQ', 'VideoCard' : 'NVidia' } }"); //something like that o.SetByPath("Drivers.VideoCard") = "Intel"; 可能吗 顺便说一句,我知道我可以做到: o["Drivers"]["VideoCard"
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drivers': {
'Mouse': 'HPQ',
'VideoCard' : 'NVidia'
}
}");
//something like that
o.SetByPath("Drivers.VideoCard") = "Intel";
可能吗
顺便说一句,我知道我可以做到:
o["Drivers"]["VideoCard"] = "Intel";
但这不是我想要的。以下方法将从与您在问题中提供的路径类似的路径中获取内部对象/值:
public static object GetObjectFromPath(dynamic obj, string path)
{
string[] segments = path.Split('.');
foreach(string segment in segments)
obj = obj[segment];
return obj;
}
你可以这样称呼它:
// Providing that 'o' is the JObject in your question
object result = GetObjectFromPath(o, "Drivers");
// result will be of type JObject because it is an inner json object
JObject innerObject = (JObject)result;
object value = GetObjectFromPath(o, "Drivers.VideoCard");
// You may also do GetObjectFromPath(innerObject, "VideoCard");
// value will be of type JValue because it is a json value
JValue innerValue = (JValue)result;
// You may get the .NET primite value calling the 'Value' property:
object stringValue = (string)innerValue.Value;
//You may also set the value
innerValue.Value = "Intel";
这里可以使用和方法来实现基本相同的效果
static void Main(string[] args)
{
JObject obj = JObject.Parse(@"{
'CPU': 'Intel',
'Drivers': {
'Mouse': 'HPQ',
'VideoCard' : 'NVidia'
}
}");
Console.WriteLine(obj);
JToken token = obj.SelectToken("Drivers.VideoCard");
token.Replace("Intel");
Console.WriteLine(obj);
}
输出:
{
"CPU": "Intel",
"Drivers": {
"Mouse": "HPQ",
"VideoCard": "NVidia"
}
}
{
"CPU": "Intel",
"Drivers": {
"Mouse": "HPQ",
"VideoCard": "Intel"
}
}
如果您愿意,可以将其放入扩展方法中
static void SetByPath(this JObject obj, string path, string value)
{
JToken token = obj.SelectToken(path);
token.Replace(value);
}
我们有java库来实现同样的功能吗?@SureshRaja我不知道。我几乎没有Java方面的经验。