`
HeLinHang
  • 浏览: 141538 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

解析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();
		}
    }
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics