json字符串与对象互转
来源:互联网 发布:网络信号无线传输器 编辑:程序博客网 时间:2024/06/04 01:22
需要的jar包:
gson-2.2.4.jar
json.jar
//json字符串转对象
//json字符串转对象@Testpublic void test5() {Gson gson = new Gson();String string;try {string = Utils.getStringByReadFile("city.json");CityInfo citys = gson.fromJson(string, CityInfo.class);List<City> list = citys.getCitys();for (City city : list) {System.out.print(city.getCode());}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
封装了一个Utils类,目的是读取json文件的字符串
public class Utils {public static String getStringByReadFile(String name) {InputStream fis = Utils.class.getClassLoader().getResourceAsStream(name);StringBuilder sb = new StringBuilder();byte[] bytes = new byte[128];int len = 0;try {while( (len = fis.read(bytes)) != -1){sb.append(new String(bytes,0,len));}} catch (IOException e) {e.printStackTrace();}return sb.toString();}}
json文件:
{"info": [{"code": "C","key": "028","nearest": "NO","value": "成都"},{"code": "N","key": "0771","nearest": "NO","value": "南宁"},{"code": "L","key": "0772","nearest": "NO","value": "柳州"},{"code": "G","key": "0773","nearest": "NO","value": "桂林"}],"resultCode": "0","resultInfo": "SUCCESS"}一个city 一个cityInof类:
public class City {private String code;private String key;private String nearest;private String value;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getKey() {return key;}public void setKey(String key) {this.key = key;}public String getNearest() {return nearest;}public void setNearest(String nearest) {this.nearest = nearest;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}}
public class CityInfo {private List<City> info;public List<City> getCitys() {return info;}public void setCitys(List<City> citys) {this.info = citys;}}
运行结果(因为只是获取city.getCode()所以结果是:
0 0
- Json字符串与Json对象互转
- Json字符串与Json对象互转
- Json对象与Json字符串互转
- Json对象与Json字符串互转
- Json对象与Json字符串互转
- JSON对象与JSON字符串互转
- Json对象与Json字符串互转
- Json对象与Json字符串互转
- JSON--json字符串与json对象互转
- Java对象与JSON字符串互转
- json字符串与JavaBean对象互转
- Java对象与JSON字符串互转
- Json字符串与java对象互转
- json字符串与对象互转
- json字符串与java对象互转
- json字符串与java对象互转
- json字符串与java对象互转
- java对象与JSON字符串互转
- 一个“-”引发的血案
- LeapMotion简单介绍及图形获取
- BottomNavigationBar
- JS数组 全解析(创建数组的方法、稀疏数组、检测数组、数组元素的增删、常用的数组方法)
- Linux下JDK配置
- json字符串与对象互转
- 正交实验测试用例利器——pict
- sharding-jdbc源码阅读之Adapter
- 坚持#第168天~辛德勒、珍惜。刘旭晔农村美食天天吃货项目感慨
- 中科院大牛博士是如何进行文献检索和阅读(好习惯受益终生)
- 盘符设备名互相转换
- Java学习笔记 --- 匹配出括号中的字符和数字
- Unity3D IPV6的处理
- 移动Oracle数据文件(Windows操作记录)