Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按路径设置JSON属性_C#_Json_Json.net - Fatal编程技术网

C# 按路径设置JSON属性

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"

有没有办法使用Json.NET通过路径设置属性

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方面的经验。