JSON数据转换
2015-09-27 13:44
661 查看
用到的开源项目:https://github.com/google/gson
news类:
View Code
把对象转换成json:
json内容:就是字符串
{"content":"主体","desc":"副标题","title":"标题","id":1000}
json转成对象:
list集合==>json:
json==>集合List:
项目地址:
https://github.com/amorypepelu/JsonDemo
news类:
package com.example.jsondemo.domain; public class News { private int id; private String title; private String desc; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public News(int id, String title, String desc, String content) { super(); this.id = id; this.title = title; this.desc = desc; this.content = content; } public News() { } public News(String title, String desc, String content) { super(); this.title = title; this.desc = desc; this.content = content; } }
View Code
把对象转换成json:
private String objToJson() { News news = new News(1000, "标题", "副标题", "主体"); String gString = g.toJson(news); Log.i("GSON", gString); return gString; }
json内容:就是字符串
{"content":"主体","desc":"副标题","title":"标题","id":1000}
json转成对象:
private News jsonToObj(String json) { Log.i("GSON", "json to obj"); News news = g.fromJson(json, News.class); Log.i("GSON", news.toString()); return news; }
list集合==>json:
private String listToJson() { List<News> list = new ArrayList<News>(); list.add(new News(10001, "标题1", "副标题1", "主体1")); list.add(new News(100012, "标题12", "副标题12", "主体12")); list.add(new News(100013, "标题13", "副标题13", "主体13")); list.add(new News(100014, "标题14", "副标题14", "主体14")); list.add(new News(100015, "标题15", "副标题15", "主体15")); String gList = g.toJson(list); Log.i("GSON", gList); return gList; }
json==>集合List:
private List<News> jsonToList(String json) { // import java.lang.reflect.Type; Type type = new TypeToken<List<News>>() { }.getType(); List<News> list = g.fromJson(json, type); for (News news : list) { Log.i("GSON", news.getTitle() + news.getDesc()); } return list; }
项目地址:
https://github.com/amorypepelu/JsonDemo
相关文章推荐
- JavaScript高级程序设计之面向对象的程序设计之创建对象之 构造函数模式第6.2.2讲笔记
- JavaScript高级程序设计之面向对象的程序设计之创建对象之工厂模式第6.2.1讲笔记
- javascript中的array对象属性及方法
- javascript中的算数运算
- 标 题: JavaScript真的要一统江湖了
- json学习初体验--第三者jar包实现bean、List、map创json格式
- javascript中的数据类型---数字
- JavaScript高级程序设计之面向对象的程序设计之理解对象第6.1讲笔记
- JavaScript高级程序设计之引用类型之单体内置对象之Math对象第5.7.2讲笔记
- JS实现横向与竖向两个选项卡Tab联动的方法
- JSONKit解析
- JavaScript高级程序设计之引用类型之单体内置对象之Global对象第5.7.1讲笔记
- JavaScript 闭包
- JS实现带鼠标效果的头像及文章列表代码
- 通过超链接传值到jsp页面,用el表达式获取时中文乱码
- 关于voller框架的json image netimage
- html 自动生成数字------document.write(c) js写在 html里面
- javascript 比量str今天的日期是,参数diff
- JS实现仿新浪黄色经典滑动门效果代码
- JavaScript作用域以及闭包(一)