2012-02-02 73 views
-1

我想解析通过IIS从我的asmx webservice接收的json字符串。我收到的字符串如下图所示:解析来自asmx的json问题

"{\"Name\":\"Waqas Aslam\",\"Company\":\"ABC Systems AB\",\"Address\":\"myStreet 4\",\"Phone\":\"123456\",\"Country\":\"Sweden\"}" 

的问题是,我可以成功地检索响应字符串,但我无法解析它。这里是我的代码:

try{ 
     InputStream source = getJson(URL); 
     String s = streamToString(source); 

     Log.i(TAG, s); 


     GsonBuilder gsonb = new GsonBuilder(); 
     Gson gson = gsonb.create(); 

     JSONObject j = new JSONObject(s); 
     Employee em = gson.fromJson(j.toString(), Employee.class); 
     lblResult.setText(em.Company);   
} 
catch (Exception e) { 
    Log.e(TAG, e.toString()); 
    } 

这里的方法streamToString:

public static String streamToString(InputStream is) { 
    //as per 64K size 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is), 65728); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
     } 
     catch (IOException e) { e.printStackTrace(); } 
     finally { 
      try { is.close(); } 
      catch (Exception e) { e.printStackTrace(); } 
     } 

     return sb.toString(); 
    } 

和这里的类员工:

import com.google.gson.annotations.SerializedName; 

    public class Employee { 

      @SerializedName("Name") 
      public String Name; 

      @SerializedName("Company") 
      public String Company; 

      @SerializedName("Address") 
      public String Address; 

      @SerializedName("Phone") 
      public String Phone; 

      @SerializedName("Country") 
      public String Country; 
    } 

这里,我发现了异常:

02-02 10:08:28.877: E/TestJSON(3223): org.json.JSONException: Value {"Name":"Waqas Aslam","Company":"ABC Systems AB","Address":"myStreet 4","Phone":"123456","Country":"Sweden"} of type java.lang.String cannot be converted to JSONObject 

如果我手动(通过代码)提供json字符串到JSONObject,那么它工作正常,但不是与我从服务器接收到的字符串。有什么我需要改变在服务器端? 如果你愿意,你可以尝试从我的测试服务器获取json使用HttpPost从这个URL http://test1.phoniro.se/AndroidTestWebService/Service.asmx/TestJSON2

回答

0

这里的东西,你在那里的JSON字符串是无效的。 删除所有的转义字符(即\"),并尝试将其更改为以下:

{ 
    "Name": "WaqasAslam", 
    "Company": "ABCSystemsAB", 
    "Address": "myStreet4", 
    "Phone": "123456", 
    "Country": "Sweden" 
} 

因此,要回答你的问题,修改服务器端出示有效JSON。我上面的例子是完全有效的JSON,你不应该有任何问题与Gson解析它。 Here's您可以在不确定时使用该网站验证您的JSON输出。

+0

但事情是,如果我测试从JQuery服务器接收的json字符串,它工作正常。 JQuery是否忽略/忽略转义字符本身? – waqaslam 2012-02-02 16:01:15

+0

@Waqas我无法确定JQuery是否正确处理转义字符,但我可以告诉你,Gson不会。 – 2012-02-02 16:05:02

+0

嗯,反正谢谢。其实我已经得到它在几个小时前通过修改服务器端的工作,你的答案证实这是Json字符串我收到问题 – waqaslam 2012-02-02 16:14:00