【发布时间】:2016-04-26 04:29:48
【问题描述】:
目前在 C# 中创建 JSON 字符串并尝试使用 WebClient 将其发送到 Web API 时遇到问题。
目前我有几种方法,首先是可行的方法。使用 POSTMAN 将以下文本数据集发送到 API 可以正常工作:
POSTMAN 数据集 - 这适用于 POSTMAN
{ "record":
{
"form_id": "efe4f66f-b57c-4497-a370-25c0f3d8746a",
"status": "240",
"latitude": -82.638039,
"longitude": 27.770787,
"form_values":
{
"833b": "99999",
"683b": "9999999",
"fa37": "Testing",
"b2e3": "Testing"
}
}
}
在 C# 中,我使用了几种不同的方法来构建这种刺痛,但收效甚微。
C# 列表方法 - Newtonsoft.Json.Serialization
首先是构建一个List,然后使用Newtonsoft.Json来玩它:
List<Parent> DataList = new List<Parent>();
List<Child> Form = new List<Child.formvalues>();
var Formvals = new Child.formvalues
{
ActionDescription = Row.ActionDescription,
ActionNotes = Row.ActionNotes,
ActionID = Row.ActionID,
AssetID = Row.AssetID
};
Form.Add(Formvals);
var DataElement = new Parent
{
form_id = AppFormID,
latitude = Lat,
longitude = Long,
status = Row.Status,
form_values = Form
};
DataList.Add(DataElement);
string json = JsonConvert.SerializeObject(DataList.ToArray());
此代码产生以下字符串:
[
{\"form_id\":\"efe4f66f-b57c-4497-a370-25c0f3d8746a\",
\"latitude\":-82.638039,
\"longitude\":27.770787,
\"status\":239,
\"form_values\":[
{\"833b\":99999,
\"683b\":9999999,
\"fa37\":\"Testing\",
\"b2e3\":\"Testing\"
}]
}
]
我正在尝试的另一个尝试是以下,我认为这是迄今为止最接近的:
C# - 字符串构建方法
string Content = @"{ "
+ "\"record\": {"
+ "\"form_id\": "\"" + AppFormID + ""\","
+ "\"status\": "\"" + Row.Status + ""\","
+ "\"latitude\": "+ Lat + ","
+ "\"longitude\": "+ Long + ","
+ "\"form_values\": {"
+ "\"833b\": "\""+Row.AssetID +""\","
+ "\"683b\": "\""+Row.ActionID + ""\","
+ "\"fa37\": "\""+Row.ActionDescription + ""\","
+ "\"b2e3\": "\""+Row.ActionNotes + ""\""
+ "}"
+ "}"
+ "}";
该行导致:
{ \"record\":
{
\"form_id\": \"efe4f66f-b57c-4497-a370-25c0f3d8746a\",
\"status\": \"239\",
\"latitude\": -82.638039,
\"longitude\": 27.770787,
\"form_values\":
{
\"833b\": \"99999\",
\"683b\": \"9999999\",
\"fa37\": \"Testing\",
\"b2e3\": \"Testing\"
}
}
}
问题!
那么问题来了,有人能帮我实现我放入 POSTMAN 的第一个 JSON 格式吗?
更新 - 下午 6:40
Web 客户端代码 c# AppURLRef 在代码中进一步设置,并且在调试器中似乎是正确的。 json 是测试的结果。
var http = new WebClient();
http.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var response = http.UploadString(AppURLRef, "POST", json);
更新结果
"[{\"record\":{\"form_id\":\"efe4f66f-b57c-4497-a370-25c0f3d8746a\",
\"latitude\":-82.638039,
\"longitude\":27.770787,
\"status\":\"240\",
\"form_values\":
[{\"833b\":\"99999\",
\"683b\":\"9999999\",
\"fa37\":\"Testing\",
\"b2e3\":\"Testing\"}]}}]"
【问题讨论】: