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());
    	}
    }
    
    
  • 相关阅读:
    css 负边距 小记
    javascript Array 方法学习
    使用自定义字体 @font-face 小试
    mongodb 基本指令学习 (2)
    mongodb 基本指令学习
    ASP.NET MVC AJAX调用JsonResult方法并返回自定义错误信息
    MVC MVVM Knockout 常遇问题总结
    关于 mvc 中 连字符
    在一般处理程序中,把Form Post过来的表单集合转换成对象 ,仿 MVC post,反射原理
    EF经验分享_jimmyzzc
  • 原文地址:https://www.cnblogs.com/wardensky/p/4528960.html
Copyright © 2011-2022 走看看