2013-03-01 75 views
-1

我有以下代碼:問題解析JSON對象響應於C#對象

[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 \「:[{\ 「對象ID \」:28,\ 「globalId \」:\ 「{740490C6-77EE-4AC0-9561-5EBAACE3A0A7} \」,\ 「成功\」:真}]}」

我創建的一旦我反序列化它後,下面的類將保存該對象:

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; } 
} 

但是當我運行代碼時,addResult對象包含默認對象值而不是json對象值。

這個特定響應的API是在這裏: http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/fsadd.html

上得到這個工作的任何幫助感激

+0

該字符串與您的RootObject類匹配,但是您在代碼示例中反序列化爲AddResult。 – bmavity 2013-03-01 19:52:38

+0

感謝bmavity,當我將它改爲反序列化到RootObject時它工作得很好 – 2013-03-01 20:26:20

回答

0

變化

client.Headers["Content-type"] = "application/x-www-form-urlencoded"; 

client.Headers["Content-type"] = "Application/json"; 
1

嘗試這

RootObject addResults=jss.Deserialize<RootObject>(aRespStr); 

或與之相似,你可以試試這個

List<AddResult> addResults = jss.Deserialize<List<AddResult>>(aRespStr); 

因爲你在你的JSON響應返回AddResult的名單。

並將內容類型更改爲應用程序/ json

+0

請標記爲答案。如果你有你的解決方案 – Sachin 2013-03-11 21:18:30