當在C#中創建JSON字符串並嘗試使用WebClient將其發送到Web API時,正面臨一個問題。將C#JSON字符串添加到Web API
目前我有幾個方法,首先是一個工作。使用郵差通過發送文本以下數據集的API正常工作:
郵差數據集 - 這部作品在郵差
{ "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
首先是建立一個列表,然後使用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\"
}]
}
]
我嘗試的另一個嘗試是followi NG,這在我看來是最接近至今:
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\"
}
}
}
的問題!
所以現在的問題,是有人能夠幫助我實現我投入郵差正好第一JSON格式?
更新 - 6:40 PM
Web客戶端代碼的C# AppURLRef在代碼中設置進一步上漲,似乎是在調試器中正確。 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\"}]}}]"
唯一的問題是,833b和683b不能是變量名稱,因爲它們以數字開頭。我假設你的意思是JsonConvert.SerializeObject(data);在使用中? – Caz1224
刪除那些我仍然得到從服務器反擊說,它不喜歡它 – Caz1224
我不得不廢除WebClient()它不會工作。我把RestClient放進去,然後用你的方法形成了JSON,它完美地工作。謝謝您的幫助 – Caz1224