对c#对象发出解析JSON对象响应
本文关键字:对象 JSON 响应 | 更新日期: 2023-09-27 18:01:59
我有以下代码:
[WebMethod]
public bool AddUser(long warnId, double longitude, double latitude)
{
try
{
string jsonFeature = string.Empty;
jsonFeature += "[{'geometry': {'x': " + longitude + ",'y': " + latitude +
",'spatialReference': {'wkid': 4326}},'attributes': {'UID': '";
jsonFeature += warnId + "','Latitude': '" + latitude + "','Longitude': '" + longitude + "'}}]";
string reqURL = System.Configuration.ConfigurationManager.AppSettings["WARNURL"] + "addFeatures";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
client.Encoding = System.Text.Encoding.UTF8;
var collection = new System.Collections.Specialized.NameValueCollection();
collection.Add("f", "json");
collection.Add("features", jsonFeature);
byte[] response = client.UploadValues(reqURL, "POST", collection);
MemoryStream stream = new MemoryStream(response);
StreamReader reader = new StreamReader(stream);
string aRespStr = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
AddResult addResult = jss.Deserialize<AddResult>(aRespStr);
return aRespStr.Contains("true") && aRespStr.Contains("success");
}
}
catch(Exception e)
{
string message = e.Message;
return false;
}
}
当我运行它时,字符串aRespStr是:
"{'"addResults '":[{' '"objectId '":28日"globalId '",'"{740490 c6 - 77 - ee - 4 - ac0 - 9561 - 5 - ebaace3a0a7}成功'",'"'":真}}"
我创建了以下类来保存对象,一旦我反序列化它:
public class Error
{
public int code { get; set; }
public string description { get; set; }
}
public class AddResult
{
public int objectId { get; set; }
public object globalId { get; set; }
public bool success { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<AddResult> addResults { get; set; }
}
但是当我运行代码时,addressult对象包含默认对象值而不是json对象值。
这个特殊响应的api在这里:http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/fsadd.html
任何帮助让这个工作是非常感谢
试试这个
RootObject addResults=jss.Deserialize<RootObject>(aRespStr);
或者类似的
List<AddResult> addResults = jss.Deserialize<List<AddResult>>(aRespStr);
,因为你正在返回json响应中的地址结果列表。
并更改内容类型为application/json
change
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
client.Headers["Content-type"] = "Application/json";