我有下一个JObject:
{
"Attrib1":"Value1",
"Atrrib2":"Value2",
"Inners": [
{
"InnerAttrib1":"InnerValue1",
"InnerAttrib2":"InnerValue2"
},
{
"InnerAttrib1":"InnerValue2",
"InnerAttrib2":"InnerValue3"
},
{
"InnerAttrib1":"InnerValue4",
"InnerAttrib2":"InnerValue5"
}
],
"Attrib3": "anotherThing"
}
我有一个提取"Inner"值并进行REST调用的函数,我的REST服务一次只支持一个"Inners"属性,例如:
{
"Attrib1":"Value1",
"Atrrib2":"Value2",
"Inners": [
{
"InnerAttrib1":"InnerValue2",
"InnerAttrib2":"InnerValue3"
}
],
"Attrib3": "anotherThing"
}
所以。。。我做了一个函数,从"Inners"中提取一个值:
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"就是这样的:
"Inners": "{
"InnerAttrib1":"InnerValue1",
"InnerAttrib2":"InnerValue2"
}"
如何删除括号开头和结尾的引号,或者如果你能向我建议一些替代方案,谢谢!
尝试一些我找到的方法:
auxiliarJson.SelectToken("Inners").Replace(JToken.Parse("["+arraytoMerge[innerCount].ToString()+"]")); //My Solution!
我的建议是不要使用JObject,除非您别无选择。
如果你知道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
}
}