我在android上做一个客户端接受http返回数据。得到一个String 类型 mess,由JSONobject.toString 拿到的。 导入java json常用包(6个)后
android中的解析代码如下:
String mess = "{"loginuser":[{"password":"123","person":{"address":"4654","id":1,"name":"ttjxffda","phone":"1212"},"status":0,"username":"ttjxtjx"}],"loginresult":"success"}";
JSONObject jsonObject = JSONObject.fromObject(mess);
String state = (String) jsonObject.get("loginresult");
if (state.equals("success")) {
JSONArray jsonArray = jsonObject.getJSONArray("loginuser");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
Libuser user = new Libuser();
user.setUsername(item.getString("username"));
user.setPassword(item.getString("password"));
user.setStatus(item.getInt("status"));
}
}
在android单元测试时报异常 java.lang.IllegalArgumentException: already added: Lorg/apache/commons/collections/ArrayStack; 项目出错无法测试
在java项目中测试通过。
我知道这是因为引入了重复包,我删了commons-collections.jar (3.2)这个包,结果报找不到类异常:
case by:NoClassDefFoundError org.apache.commons.map.listOrderedMap。
没法解决。纠结。求高人指点
我有常识过用android自带的json类,但是它解析不了mess字符串,
org.json.JSONException: Expected ':' after " at character 7 of {"loginuser":[{"password":"123","person":{"address":"4654","id":1,"name":"ttjxffda","phone":"1212"},"status":0,"username":"ttjxtjx"}],"loginresult":"success"}
at org.json.JSONTokener.syntaxError(JSONTokener.java:446)
at org.json.JSONTokener.readObject(JSONTokener.java:375)
at org.json.JSONTokener.nextValue(JSONTokener.java:96)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at cec.jmu.test.LoginTest.getLoginstate(LoginTest.java:38)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
mess内容代码中有。outprint结果:{"loginuser":[{"password":"123","person":{"address":"4654","id":1,"name":"ttjxffda","phone":"1212"},"status":0,"username":"ttjxtjx"}],"loginresult":"success"}
生成mess的代码,Libuser中有个Person对象。
Libuser loginuser=LibuserService.getLoginUser(user);
System.out.println(loginuser.toString());
JSONObject jsonObject = new JSONObject();
JSONObject item = new JSONObject();
JSONArray jsonArray = new JSONArray();
item.put("username", loginuser.getUsername());
item.put("password", loginuser.getPassword());
item.put("status", loginuser.getStatus());
jsonArray.element(loginuser);
jsonObject.put("loginuser", jsonArray);