javaMap List Bean 转 JSON
Posted Jack小强
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaMap List Bean 转 JSON相关的知识,希望对你有一定的参考价值。
需要jar
json-lib.jar
http://download.csdn.net/detail/yjqyyjw/9800968
User
package demo;
public class User
private String username;
private String password;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
测试
package demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonTest
static List<User> list;
static Map<String, Object> map;
static User user1;
static User user2;
public static void main(String[] args)
new JsonTest().initUser();
/**
* A:普通JavaBean转成json格式
* 1.转成JSONArray类型
*/
JSONArray json = JSONArray.fromObject(user1);
// ["password":"1111","username":"yjq1"]
// 在js文件取数据
// $.getJSON("http://localhost:8080/jQueryDemo/servlet/listervlet",null,function(data)
//
// alert(data[0].username);
// alert(data[0].password);
// );
/**
* 2.转成JSONObject类型
*/
JSONObject jsonObj = JSONObject.fromObject(user1);
// "password":"1111","username":"yjq1"
// 在js文件取数据 alert(data.username); alert(data.password);
/**
* B:List转成json格式
* 1.转成JSONArray类型
*/
JSONArray jsonList = JSONArray.fromObject(list);
// ["password":"1111","username":"yjq1","password":"2222","username":"yjq2"]
// js中取数据:alert(alert(data[0].username));
/**
* 2.转成JSONObject类型
*/
JSONObject jsonListObj = new JSONObject();
jsonObj.put("list", list);
jsonObj.put("u", user1);
// "list":["password":"1111","username":"yjq1","password":"2222","username":"yjq2"],"u":"password":"1111","username":"yjq1"
// js中取数据:alert(data.list[0].username);
/**
* C:Map转成json格式
* 1.转成JSONArray类型
*/
JSONArray jsonMap = JSONArray.fromObject(map);
// ["list":["password":"1111","username":"yjq1","password":"2222","username":"yjq2"],"u":"password":"1111","username":"yjq1"]
// js中取数据:alert(data[0].list[0].username);
/**
* 2.转成JSONObject类型
*/
JSONObject jsonMapObj = JSONObject.fromObject(map);
// "user":["password":"1111","username":"yjq1","password":"2222","username":"yjq2"],"u":"password":"1111","username":"yjq1"
// js中取数据:alert(data.user[0].username);
public void initUser()
user1 = new User();
user1.setUsername("yjq1");
user1.setPassword("1111");
user2 = new User();
user2.setUsername("yjq2");
user2.setPassword("2222");
list = new ArrayList<User>();
list.add(user1);
list.add(user2);
map = new HashMap<String, Object>();
map.put("list", list);
map.put("user1", user1);
以上是关于javaMap List Bean 转 JSON的主要内容,如果未能解决你的问题,请参考以下文章