您的位置:首页 > Web前端 > JavaScript

JSON数据转换

2015-09-27 13:44 661 查看
用到的开源项目:https://github.com/google/gson

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: