关闭

将数据转换为json格式代码

1616人阅读 评论(0) 收藏 举报
分类:

本文数据转json格式的入门代码,创建java文件即可

用于将实体信息封装成json格式数据
使用工具:myeclipse
导入包gson.jar
项目结构:


SchoolInfo.java
public class SchoolInfo {
	private String mSchoolName;
	
	public void setSchoolName(String schoolName){
		this.mSchoolName = schoolName;
	}
	
	public String getSchoolName(){
		return mSchoolName;		
	}
}
Person.java
import java.util.List;

public class Person {
	private String mName;
	private int mAge;
	private String mUrl;
	private List<SchoolInfo> mSchoolInfo;
	
	/*get方法*/
	public String getName(){
		return mName;
	}
	public int getAge(){
		return mAge;
	}
	public String getUrl(){
		return mUrl;
	}
	public List<SchoolInfo> getSchoolInfo(){
		return mSchoolInfo;
	}
	
	/*set方法*/
	public void setName(String name){
		this.mName = name;
	}
	public void setAge(int age){
		this.mAge = age;
	}
	public void setUrl(String url){
		this.mUrl = url;
	}
	public void setSchoolInfo(List<SchoolInfo> schoolInfo){
		this.mSchoolInfo = schoolInfo;
	}	
}
Result.java
import java.util.List;


public class Result {
	private int mResult;
	private List<Person> mPersonData;
	
	/*get方法*/
	public int getResult(){
		return mResult;
	}
	public List<Person> getPersonData(){
		return mPersonData;
	}
	
	/*set方法*/
	public void setResult(int result){
		this.mResult = result;
	}
	public void setPersonData(List<Person> personData){
		this.mPersonData = personData;
	}
	
}
TestJson.java
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
/**
 * 生成json代码,封装实体数据
 * @author xiaoyuer
 *
 */
public class TestJson {
	
	/*封装的概念,一级管理一级的封装,不要跨级封装*/
	public static void main(String[] args){	
		Result result = new Result();
		result.setResult(1);
		
		List<Person> personData = new ArrayList<Person>();
		result.setPersonData(personData);
		
		Person person1 = new Person();
		person1.setName("nate");
		person1.setAge(12);
		person1.setUrl("http://h.hiphotos.baidu.com/image/pic/item/6c224f4a20a446239e8d311c9b22720e0cf3d70d.jpg");
		
		List<SchoolInfo> schoolInfos = new ArrayList<SchoolInfo>();
		SchoolInfo schoolInfo1 = new SchoolInfo();
		SchoolInfo schoolInfo2 = new SchoolInfo();
		schoolInfo1.setSchoolName("北大");
		schoolInfo2.setSchoolName("清华");			
		schoolInfos.add(schoolInfo1);
		schoolInfos.add(schoolInfo2);
		
		person1.setSchoolInfo(schoolInfos);
		personData.add(person1);	
		Gson gson = new Gson();
		
		//打印,通过toJson方法将所有的数据转化为json格式
		System.out.println(gson.toJson(result));
		
		
	}
	
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:57789次
    • 积分:1051
    • 等级:
    • 排名:千里之外
    • 原创:99篇
    • 转载:35篇
    • 译文:1篇
    • 评论:17条
    最新评论