List<Map<Title, List<TitleSon>>>转换json格式
List<Map<Title, List<TitleSon>>> =[{Title [id=1, title=主页]=[]}, {Title [id=2, title=医疗产品]=[Title_son [id=1, name=自动注射器, title_id=2], Title_son [id=2, name=血压器, title_id=2], Title_son [id=3, name=血糖仪, title_id=2]]}, {Title [id=3, title=智能家居]=[Title_son [id=4, name=智能窗台, title_id=3], Title_son [id=5, name=智能门, title_id=3], Title_son [id=6, name=智能电灯, title_id=3], Title_son [id=7, name=智能沙发, title_id=3]]}, {Title [id=4, title=技术支持]=[]}, {Title [id=5, title=公司简介]=[]}];在线等。。。
public class Title implements Serializable {
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
@Override
public String toString() {
return "Title [id=" + id + ", title=" + title + "]";
}
public void setTitle(String title) {
this.title = title;
}
private Integer id;
private String title;
}
/**
**
**
**
**/
public class TitleSon implements Serializable {
@Override
public String toString() {
return "Title_son [id=" + id + ", name=" + name + ", title_id="
+ title_id + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTitle_id() {
return title_id;
}
public void setTitle_id(Integer titleId) {
title_id = titleId;
}
private Integer id;
private String name;
private Integer title_id;
}
--------------------编程问答-------------------- 用任意一个json的java库转一下 有什么问题吗?
比如:gson
不太明白。
--------------------编程问答--------------------
public static String List2JSONStr(List list) {--------------------编程问答-------------------- 用gson一句话搞定
if (list == null || list.isEmpty()) {
return "[]";
}
int len = list.size();
StringBuffer strBuf = new StringBuffer("[ ");
Object obj = null;
JSONObject jsonObj = null;
for (int i = 0; i < len; i++) {
obj = list.get(i);
// if (!(obj instanceof Map)) continue;
if (obj instanceof Map)
jsonObj = JSONObject.fromObject(obj);
else
jsonObj = JSONObject.fromObject(Bean2Map(obj));
strBuf.append(jsonObj.toString());
strBuf.append(",");
}
strBuf.deleteCharAt(strBuf.length() - 1).append(" ]");
return strBuf.toString();
}
public static Map Bean2Map(Object bean) {
Map map = new HashMap();
Method[] methods = bean.getClass().getMethods();
String methodName = "", fieldName = "";
Object fieldValue = null;
for (int i = 0; i < methods.length; i++) {
methodName = methods[i].getName();
if (methodName.length() >= 4 && methodName.substring(0, 3).equals("get")) {
fieldName = methodName.substring(3, 4).toLowerCase()
+ methodName.substring(4);
try {
fieldValue = methods[i].invoke(bean, new Object[] {});
} catch (Exception e) {
// logger.error("Bean2Map error:"+e);
fieldValue = null;
continue;
}
if (fieldValue != null) {
map.put(fieldName, fieldValue);
}
}
}
return map;
}
new Gson().toJson(m)
可以是list 可以是map
补充:Java , Java EE