-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
但事情是,如果我测试从JQuery服务器接收的json字符串,它工作正常。 JQuery是否忽略/忽略转义字符本身? – waqaslam 2012-02-02 16:01:15
@Waqas我无法确定JQuery是否正确处理转义字符,但我可以告诉你,Gson不会。 – 2012-02-02 16:05:02
嗯,反正谢谢。其实我已经得到它在几个小时前通过修改服务器端的工作,你的答案证实这是Json字符串我收到问题 – waqaslam 2012-02-02 16:14:00