解析JSON数据
工具类:JsonUtils
package cn.edu.utils; import java.io.IOException; import cn.edu.bean.LoginResult; import cn.edu.bean.User; import com.google.gson.Gson; public class JsonUtils { public void parse(String jsonData) throws IOException { Gson gson=new Gson(); LoginResult result=gson.fromJson(jsonData,LoginResult.class); System.out.println(result.getResult()); /** * method one */ // Gson gson=new Gson(); // User user=gson.fromJson(jsonData,User.class); // System.out.println(user.getUserName()); // System.out.println(user.getPassword()); // /** // * method two // */ // Gson gson=new Gson(); // Type listType=new TypeToken<LinkedList<User>>(){}.getType(); // LinkedList<User> users=gson.fromJson(jsonData,listType); // for(User user:users){ // System.out.println(user.getUserName()); // System.out.println(user.getPassword()); // // } // // // /** // * method three // *开始解析数组 // *开始解析对象 // *开始解析键值对 // *开始解析键值对 // *解析对象结束 // *开始解析对象 // *开始解析键值对 // *开始解析键值对 // *解析对象结束 // *解析数组结束 // */ // // JsonReader reader=new JsonReader(new StringReader(jsonData)); // reader.beginArray(); // while(reader.hasNext()) // { // reader.beginObject(); // while(reader.hasNext()) // { // String tagName=reader.nextName(); // if(tagName.equals("userName")) // { // System.out.println(reader.nextString()); // }else if(tagName.equals("password")) // { // System.out.println(reader.nextString()); // } // // } // reader.endObject(); // } // reader.endArray(); } }
对于方法一的解析,还要增加User类
package cn.edu.bean; public class User { private String userName; private int password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getPassword() { return password; } public void setPassword(int password) { this.password = password; } }
package cn.edu.json; import java.io.IOException; import android.app.Activity; import android.os.Bundle; import cn.edu.utils.JsonUtils; public class JsonActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //String jsonData="{\"userName\":\"hello\",\"password\":123456}"; //String jsonData="[{\"userName\":\"hello\",\"password\":123456},{\"userName\":\"hello\",\"password\":123456}]"; String jsonData="{\"result\":\"success\"}"; try { new JsonUtils().parse(jsonData); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30