如何从JArray中提取一些值并放入JSon中

时间:2014-10-07 15:01:39

标签: c# json json.net

我有下一个JObject:

{
  "Attrib1":"Value1",
  "Atrrib2":"Value2",
  "Inners": [
    {
      "InnerAttrib1":"InnerValue1",
      "InnerAttrib2":"InnerValue2"
    },
    {
      "InnerAttrib1":"InnerValue2",
      "InnerAttrib2":"InnerValue3"
    },
    {
      "InnerAttrib1":"InnerValue4",
      "InnerAttrib2":"InnerValue5"
    }
  ],
  "Attrib3": "anotherThing"
}

我有一个提取“内部”值并进行REST调用的函数,我的REST服务当时只支持一个“内部”属性,就像那样:

   {
      "Attrib1":"Value1",
      "Atrrib2":"Value2",
      "Inners": [
        {
          "InnerAttrib1":"InnerValue2",
          "InnerAttrib2":"InnerValue3"
        }
      ],
      "Attrib3": "anotherThing"
    }

所以...我已经创建了一个从“内部”中提取一个值的函数:

public List<string> fillClient(JObject request)
        {
            var auxiliarJson = new JObject();
            var arraytoMerge=new JArray();
            var listResult = new List<string>();
            clientRest.EndPoint = "ClientEndPoint";
            auxiliarJson = request;
            arraytoMerge = request.SelectToken("Inners") as JArray;            
            for (int innerCount = 0; innerCount < arraytoMerge.Count; innerCount++)
            {
              auxiliarJson.SelectToken("Inners").Replace(arraytoMerge[innerCount]);//My problem!
              clientRest.PostData = request.ToString(); //fill the data to send
              listResult.Add(clientRest.MakeRequest()); //Send the request 
            }
            return listResult;
        }

当我这样做时,我有一个错误(错误的请求),调试我发现我的“内部”就是这样:

"Inners": "{
          "InnerAttrib1":"InnerValue1",
          "InnerAttrib2":"InnerValue2"
        }"

如何在括号的开头和结尾处消除此引号,或者如果您可以向我建议一些替代方法,请多谢!

2 个答案:

答案 0 :(得分:1)

尝试一些事情我找到了办法:

auxiliarJson.SelectToken("Inners").Replace(JToken.Parse("["+arraytoMerge[innerCount].ToString()+"]")); //My Solution!

答案 1 :(得分:0)

除非你别无选择,否则我的建议是不能与JObject一起使用

如果你知道&#34;架构&#34;你的json(在大多数情况下你确切知道会发生什么,只是忽略意外),然后你可以在POCO中反序列化你的json。然后,您可以随意操作强类型数据,然后在需要发送时将其序列化。

public class MyClass
{
    public string Attrib1 {get; set;}
    public string Attrib2 {get; set;}
    public List<InnerClass> Inners {get; set;}
    ...
}

public class InnerClass
{
    ...
}

public void DoStuffWithInput(string input)
{
    var myObject = JsonConvert.DeserializeObject<MyClass>(input);
    foreach (InnerClass inner in myObect.Inners)
    {
        var innerJson = JsonConvert.SerializeObject(inner);
        // do stuff
    }
}