zoukankan      html  css  js  c++  java
  • 使用gson进行json转换

    Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
    示例代码如下:

    实体定义

    package com.wisdombud.gson;
    
    public class SimpleEntity {
    
    	private String testInfo;
    
    	private Boolean result;
    
    	public String getTestInfo() {
    		return testInfo;
    	}
    
    	public void setTestInfo(String testInfo) {
    		this.testInfo = testInfo;
    	}
    
    	public Boolean getResult() {
    		return result;
    	}
    
    	public void setResult(Boolean result) {
    		this.result = result;
    	}
    }
    
    
    package com.wisdombud.gson;
    
    import java.util.List;
    
    public class ComplexEntity {
    	private List<SimpleEntity> list;
    	
    	private String name;
    	
    	private int age;
    
    	public List<SimpleEntity> getList() {
    		return list;
    	}
    
    	public void setList(List<SimpleEntity> list) {
    		this.list = list;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    }
    
    

    核心代码

    package com.wisdombud.gson;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    
    public class App {
    	public static void main(String[] args) {
    		String s = test2Json();
    		System.out.println(s);
    		testFromJson();
    	}
    
    	private static String test2Json() {
    		Gson g = new Gson();
    		List<ComplexEntity> cList = new ArrayList<ComplexEntity>();
    
    		ComplexEntity entity = new ComplexEntity();
    		cList.add(entity);
    		entity.setAge(10);
    		entity.setName("name");
    		List<SimpleEntity> list = new ArrayList<SimpleEntity>();
    		entity.setList(list);
    		SimpleEntity simple = new SimpleEntity();
    		simple.setResult(true);
    		simple.setTestInfo("testinfo");
    		list.add(simple);
    
    		String s = g.toJson(cList);
    
    		return s;
    	}
    
    	public static void testFromJson() {
    
    		String json = test2Json();
    		Gson g = new Gson();
    		List<SimpleEntity> list = g.fromJson(json,
    				new TypeToken<List<SimpleEntity>>() {
    				}.getType());
    
    		System.out.println(list.size());
    	}
    }
    
    
  • 相关阅读:
    xshell 缺少mfc110u.dll
    notepad++ 常用插件
    java 发送 http post 和 get 请求(利用unirest)
    my.conf配置大全
    md5算法
    sprinboot+redis
    jq下拉插件,chosen
    springboot+idea 热部署
    Jquery 监听浏览器前进后退
    手机自带的表情入库
  • 原文地址:https://www.cnblogs.com/wardensky/p/4528960.html
Copyright © 2011-2022 走看看