将Json数据发送到服务器+反序列化问题

时间:2013-09-24 02:00:06

标签: c# json json.net

我有一个服务(服务1),它收到一个键值对列表。 。然后我将其转换为Json并发布到另一个服务(服务2),该服务序列化数据并将其作为对象进行处理。 Service1不知道密钥的值是什么。 例如,服务1获取输入字典

Name:Sample Test:TestCase1 InnerObject:{"InnerObjectType":"1", "Name":"Sample"} TestVector

我使用NewtonSoft.Json库来构建json以发布到服务2。

JObject jsonData = new JObject();
Dictionary<string,string> dict = this.GetCasiPDPTestData();
foreach (string key in dict.Keys)
{
  string value = dict[key];                   
  jsonData.Add(new JProperty(key, value));
}
string postData = jsonData.ToString();

但是,如果值为array或object类型,则将其转换为字符串,并且服务器抛出错误“无法从HTTP请求反序列化对象数据”

帖子数据看起来像(Fiddler):

{
  "Type": "1",
  "BoolParam": "True",
  "TestVector": "[\"123\",\"456\"]",
  "Text": "Surya Test 9/23/2013 3:41",
  "Number": "44",
  "InnerData": "{\"InnerMessage\": \"InnerMessage_44\",\"Things\": [{\"AdditionalType\": \"InnerAdditionalType1_44\",\"Name\": \"InnerName1_44\",\"Version\": 44,\"Url\": \"InnerUrl1_44\",\"Image\": \"InnerImage1_44\",\"Description\": \"InnerDescription1_44\"},{\"AdditionalType\": \"InnerAdditionalType2_44\",\"Name\": \"InnerName2_44\",\"Version\": 44,\"Url\": \"InnerUrl2_44\",\"Image\": \"InnerImage2_44\",\"Description\": \"InnerDescription2_44\"}]}",
  "AdditionalType": "AdditionalType_44",
  "Name": "Surya Test 9/20/2013 4:42",
  "LastUpdatedAt": 635153176425968666,
  "Version": "45",
  "Url": "Url_44",
  "Image": "Image_44",
  "Description": "Description"
}

我们可以看到数组“TestVector”和对象“InnerData”被解释为字符串。由于service1不知道key的值,解析字典以创建json以发布到service2的解决方案是什么。服务2预期的数据

{
  "Type": "1",
  "BoolParam": "True",
  "TestVector": ["123","456"],
  "Text": "Surya Test 9/23/2013 3:41",
  "Number": "44",
  "InnerData": {"InnerMessage": "InnerMessage_44","Things": [{"AdditionalType": "InnerAdditionalType1_44","Name": "InnerName1_44","Version": 44,"Url": "InnerUrl1_44","Image": "InnerImage1_44","Description": "InnerDescription1_44"},{"AdditionalType": "InnerAdditionalType2_44","Name": "InnerName2_44","Version": 44,"Url": "InnerUrl2_44","Image": "InnerImage2_44","Description": "InnerDescription2_44"}]},
  "AdditionalType": "AdditionalType_44",
  "Name": "Surya Test 9/20/2013 4:42",
  "LastUpdatedAt": 635153176425968666,
  "Version": "45",
  "Url": "Url_44",
  "Image": "Image_44",
  "Description": "Description"
}

由于

1 个答案:

答案 0 :(得分:0)

尝试使用Converter 公共类KeyValuePairConverter:Newtonsoft.Json.JsonConverter     Newtonsoft.Json.Converters的成员