1

我有一个服务(服务 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();

但是,如果值是数组或对象类型,它会被转换为字符串,服务器会抛出错误“无法从 HTTP 请求反序列化对象数据”

帖子数据看起来像(提琴手):

{
  "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 不知道键的值,解析字典以创建要发布到 service2 的 json 的解决方案是什么。服务 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"
}

谢谢

4

1 回答 1

0

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

于 2013-09-24T02:30:16.060 回答