【问题标题】:Set JSON attribute by path按路径设置 JSON 属性
【发布时间】:2015-11-20 22:59:52
【问题描述】:

有没有办法通过路径设置属性,使用 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";

但这不是我想要的。

【问题讨论】:

标签: c# json json.net


【解决方案1】:

这里可以使用JObject.SelectTokenJToken.Replace 方法来达到基本相同的效果。

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 的经验。
【解决方案2】:

以下方法将从类似于您在问题中提供的路径中获取内部对象/值:

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";

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 2019-12-14
    • 2011-08-13
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多