将新的Jtoken添加到Json Jtoken

时间:2014-05-22 08:55:11

标签: c# json

我有以下Json

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required"
  }
}

我要做的是在JToken "message": "Login Required"之下添加新的"RetryMessage": "Failed after 10 retries"

我发现这个How do you add a JToken to an JObject?并不是很有效我认为是因为错误是一个令牌,而不是一个对象,但我不确定。

我尝试过:

var JsonObj = JObject.Parse(response);
var RetryMessageJson = JToken.Parse(@"{ ""RetryMessage"" : ""UnKnown""}");
JsonObj["error"]["message"].AddAfterSelf(RetryMessageJson);

我已经尝试了上面几个版本的代码,它们都返回了以下错误消息:

Newtonsoft.Json.Linq.JProperty cannot have multiple values.

3 个答案:

答案 0 :(得分:17)

除非订单确实很重要,否则我怀疑你只想把它作为错误的另一个属性:

// Variable names edited to follow normal C# conventions
var jsonResponse = JObject.Parse(response);
jsonResponse["error"]["retryMessage"] = "Unknown";

使用您的示例JSON,结果是:

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required",
    "retryMessage": "Unknown"
  }
}

答案 1 :(得分:5)

尽管Jon Skeet的答案是100%正确的,但在您的情况下,您可以完成同样的事情,而无需明确指定确切的路径:

var jsonResponse = JObject.Parse(response);
var newProperty = new JProperty("RetryMessage", "Failed after 10 retries");
jsonResponse.Last.AddAfterSelf(newProperty);

答案 2 :(得分:0)

当您有多个属性时,这似乎按预期工作。并不是说我喜欢这些,因为它感觉很乱。

var test = JToken.Parse($"{{ \"Item1\": \"Value1\", \"Item2\": \"Value2\", \"Item3\": \"Value3\" }}");
jtokenList.Add(test);