欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Gson json,list,model互转

程序员文章站 2022-07-15 14:57:17
...
public class Person {

	private String name;
	private String age;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return name + ":" + age;
	}
}

 

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class TestMain {
	
	private static String listToJson(){
		Gson gson = new Gson();
		List<Person> persons = new ArrayList<Person>();
		for (int i = 0; i < 10; i++) {
			Person p = new Person();
			p.setName("name" + i);
			p.setAge("intvalue");
			persons.add(p);
		}
		String str = gson.toJson(persons);
		return str;
	}
	
	private static Person jsonToModelisDeit(){
		String json = "{\"name\":\"name0\",\"age\":\"0\"}";
		Gson gson = new Gson();
		Person person = gson.fromJson(json, Person.class);
		return person;
	}
	
	private static List<Person> jsonToList(){
		Gson gson = new Gson();
		String json = "[{\"name\":\"name1\",\"age\":\"intvalue\"},{\"name\":\"name2\",\"age\":\"intvalue\"},{\"name\":\"name3\",\"age\":\"intvalue\"}]";
		List<Person> ps = gson.fromJson(json, new TypeToken<List<Person>>(){}.getType());
		for(int i = 0; i < ps.size() ; i++)
		{
		     Person p = ps.get(i);
		     System.out.println(p.toString());
		}
		return ps;
		
	}

	public static void main(String[] args) {
//		String json = TestMain.listToJson();
//		System.out.println(json);
//		
//		Person model = TestMain.jsonToModelisDeit();
//		System.out.println(model.getName());
//		System.out.println(model.getAge());
		
		List<Person> plist = TestMain.jsonToList();

	}

}

 

<!-- google Gson -->
<dependency>
        <groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.6.2</version>
</dependency>