[图片上传失败...(image-6adce8-1522634020763)]
什么是JSON?
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于javascript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
现在我们就来研究一下fastJson。
Fastjson是国内著名的电子商务互联网公司阿里巴巴内部开发的用于java后台处理json格式数据的一个工具包,包括“序列化”和“反序列化”两部分,它具备如下特征
1. 速度最快,测试表明,fastjson具有极快的性能,超越任其他的java json parser。包括自称最快的jackson。
2. 功能强大,完全支持java bean、集合、Map、日期、Enum,支持范型,支持自省。
3. 无依赖,能够直接运行在Java SE 5.0以上版本
4. 支持Android。
5. 这是fastJson的网址:http://code.alibabatech.com/wiki/display/FastJSON/Overview其中包含了json数据处理的教程,jar下载地址,example样例等
JSONObject 与JSONArray
- JSONObject
json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value}
- JSONArray
json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的
Json对象中是添加的键值对,JSONArray中添加的是Json对象
例子
JSONObject object = (JSONObject) JSON.toJSON(templetBean);
String jsonStr = object.toJSONString();
/**
* Created by wanggs on 2017/7/27.
*/
public class JsonTest {
public static void main(String[] args) {
// Json对象中是添加的键值对,JSONArray中添加的是Json对象
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject1.put("001","tom");
// JSONObject 对象中添加键值对
jsonObject.put("key","value");
// 将JSONObject对象添加到json数组中
jsonArray.add(jsonObject);
jsonArray.add(jsonObject1);
System.out.println(jsonArray.toString());
// 输出结果: [{"key":"value"},{"001":"tom"}]
}
}
先来个官方例子
package com.wanggs.com.wanggs.json.fastjson;
import java.util.List;
/**
* Created by wanggs on 2017/7/27.
*/
public class Group {
private int id;
private String name;
List<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
class User{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wanggs on 2017/7/27.
*/
public class FastJsonTest {
public static void main(String[] args) {
Group group = new Group();
group.setId(0);
group.setName("admin");
User user = new User();
user.setId(001);
user.setName("guest");
User user1 = new User();
user1.setId(002);
user1.setName("root");
List<User> users = new ArrayList<User>();
users.add(user);
users.add(user1);
group.setUsers(users);
String json = JSON.toJSONString(group);
System.out.println(json);
// 输出: {"id":0,"name":"admin","users":[{"id":1,"name":"guest"},{"id":2,"name":"root"}]}
}
}
下面给出fastJson处理json数据格式的代码样例:
package test.com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wanggs.com.wanggs.json.fastjson.People;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by wanggs on 2017/7/27.
*/
public class FastJsonTestTest {
/**
* 序列化
*/
@Test
public void toJsonString() {
People people = new People("001","tom",12);
String text = JSON.toJSONString(people);
System.out.println(text);
// 输出结果: {"age":12,"id":"001","name":"tom"}
}
/**
* 反序列为Json对象
*/
@Test
public void parseJsonObject(){
String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
People people = (People) JSON.parseObject(text,People.class);
System.out.println("parseBeanObject()方法:people==" + people.getId() + "," + people.getName() + "," + people.getAge());
// 输出结果为: parseBeanObject()方法:people==001,tom,12
}
/**
* 将javaBean转化为json对象
*/
@Test
public void bean2Json(){
People people = new People("002","jack",23);
JSONObject jsonObject = (JSONObject) JSON.toJSON(people);
System.out.println("bean2Json()方法:jsonObject==" + jsonObject);
// 输出结果: bean2Json()方法:jsonObject=={"name":"jack","id":"002","age":23}
}
/**
* 全序列化 直接把java bean序列化为json文本之后,能够按照原来的类型反序列化回来。支持全序列化,需要打开SerializerFeature.WriteClassName特性
*/
@Test
public void parseJSONAndBeanEachother(){
People people = new People("002","jack",23);
SerializerFeature[] featureArr = { SerializerFeature.WriteClassName };
String text = JSON.toJSONString(people, featureArr);
System.out.println("parseJSONAndBeanEachother()方法:text==" + text);
// 输出结果:parseJSONAndBeanEachother()方法:text=={"@type":"com.wanggs.com.wanggs.json.fastjson.People","age":23,"id":"002","name":"jack"}
People people1 = (People) JSON.parse(text);
System.out.println("parseJSONAndBeanEachother()方法:People==" + people1.getId() + "," + people1.getName() + "," + people1.getAge());
// 输出结果:userObj==testFastJson001,maks,105
}
}
附:javaBean类People.java
package com.wanggs.com.wanggs.json.fastjson;
/**
* Created by wanggs on 2017/7/27.
*/
public class People {
private String id;
private String name;
private int age;
public People() {
}
public People(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
在深入Json
package test.com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wanggs.com.wanggs.json.fastjson.Address;
import com.wanggs.com.wanggs.json.fastjson.People;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
/**
* Created by wanggs on 2017/7/27.
*/
public class FastJsonTest1Test {
/**
* 数组转json字符串
*/
@Test
public void array2Json() {
String[] arr = {"bill", "green", "maks", "jim"};
String jsonText = JSON.toJSONString(arr);
System.out.println("array2Json()方法:jsonText==" + jsonText);
// 输出结果:jsonText==["bill","green","maks","jim"]
}
/**
* json格式字符串转数组
*/
@Test
public void json2Array() {
String jsonText = "[\"bill\",\"green\",\"maks\",\"jim\"]";
JSONArray jsonArray = JSON.parseArray(jsonText);
System.out.println("json2Array()方法:jsonArray==" + jsonArray);
// 输出结果:jsonArray==["bill","green","maks","jim"]
}
/**
* 数组转json格式字符串
*/
@Test
public void array2Json2() {
People people = new People("001", "tom", 12);
People people1 = new People("002", "jack", 23);
People people2 = new People("003", "mair", 22);
People[] peoples = new People[]{people, people1, people2};
String jsonText = JSON.toJSONString(peoples);
System.out.println("array2Json2()方法:jsonText==" + jsonText);
//输出结果:array2Json2()方法:jsonText==[{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
}
/**
* json格式字符串转数组
*/
@Test
public void json2Array2() {
String jsonText = "[{\"age\":12,\"id\":\"001\",\"name\":\"tom\"},{\"age\":23,\"id\":\"002\",\"name\":\"jack\"},{\"age\":22,\"id\":\"003\",\"name\":\"mair\"}]";
JSONArray jsonArr = JSON.parseArray(jsonText);
System.out.println("json2Array2()方法:jsonArr==" + jsonArr);
// 输出结果:json2Array2()方法:jsonArr==[{"name":"tom","id":"001","age":12},{"name":"jack","id":"002","age":23},{"name":"mair","id":"003","age":22}]
}
/**
* list集合转json格式字符串
*/
@Test
public void list2Json() {
List<People> list = new ArrayList<People>();
list.add(new People("001", "tom", 12));
list.add(new People("002", "jack", 23));
list.add(new People("003", "mair", 22));
String jsonText = JSON.toJSONString(list);
System.out.println("list2Json()方法:jsonText==" + jsonText);
// 输出的结果为: [{"age":12,"id":"001","name":"tom"},{"age":23,"id":"002","name":"jack"},{"age":22,"id":"003","name":"mair"}]
}
/**
* map转json格式字符串
*/
@Test
public void map2Json() {
Map map = new HashMap();
Address address1 = new Address("广东省","深圳市","科苑南路","580053");
map.put("address1", address1);
Address address2 = new Address("江西省","南昌市","阳明路","330004");
map.put("address2", address2);
Address address3 = new Address("陕西省","西安市","长安南路","710114");
map.put("address3", address3);
String jsonText = JSON.toJSONString(map, true);
System.out.println("map2Json()方法:jsonText=="+jsonText);
//输出结果:jsonText=={"address1":{"city":"深圳市","post":"580053","province":"广东省","street":"科苑南路"},"address2":{"city":"南昌市","post":"330004","province":"江西省","street":"阳明路"},"address3":{"city":"西安市","post":"710114","province":"陕西省","street":"长安南路"}}
}
/**
* json转map
*/
@Test
public void json2Map(){
String text = "{\"age\":12,\"id\":\"001\",\"name\":\"tom\"}";
Map<String,Object> map = JSON.parseObject(text);
System.out.println("json2Map()方法:map=="+map);
//输出结果:{"name":"tom","id":"001","age":12}
Set<String> set = map.keySet();
for(String key : set){
System.out.println(key+"--->"+map.get(key));
}
}
}
技巧
package com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
/**
* Created by wanggs on 2017/7/27.
*/
public class CustomText {
/**
* touser : OPENID
* msgtype : text
* text : {"content":"Hello World"}
*/
//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
private String touser;
private String msgtype;
private TextBean text;
public static class TextBean {
/**
* content : Hello World
*/
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public TextBean getText() {
return text;
}
public void setText(TextBean text) {
this.text = text;
}
}
class Test{
public static void main(String[] args) {
CustomText customText = new CustomText();
customText.setTouser("OPENID");
customText.setMsgtype("text");
CustomText.TextBean textBean = new CustomText.TextBean();
textBean.setContent("Hello World");
customText.setText(textBean);
String json = JSON.toJSONString(customText);
System.out.println(json);
//{"msgtype":"text","text":{"content":"Hello World"},"touser":"OPENID"}
}
/**
* {
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}
*/
}
归纳六种方式json转map
package com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import java.util.Set;
/**
* Created by wanggs on 2017/7/27.
*/
public class FastJsonTest1 {
public static void main(String[] args) {
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
//第一种方式
Map maps = (Map)JSON.parse(str);
System.out.println("这个是用JSON类来解析JSON字符串!!!");
for (Object map : maps.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue());
}
//第二种方式
Map mapTypes = JSON.parseObject(str);
System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");
for (Object obj : mapTypes.keySet()){
System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj));
}
//第三种方式
Map mapType = JSON.parseObject(str,Map.class);
System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");
for (Object obj : mapType.keySet()){
System.out.println("key为:"+obj+"值为:"+mapType.get(obj));
}
//第四种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map json = (Map) JSONObject.parse(str);
System.out.println("这个是用JSONObject类的parse方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第五种方式
/**
* JSONObject是Map接口的一个实现类
*/
JSONObject jsonObject = JSONObject.parseObject(str);
System.out.println("这个是用JSONObject的parseObject方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第六种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map mapObj = JSONObject.parseObject(str,Map.class);
System.out.println("这个是用JSONObject的parseObject方法并执行返回类型来解析JSON字符串!!!");
for (Object map: json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
String strArr = "{{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}," +
"{\"00\":\"zhangsan\",\"11\":\"lisi\",\"22\":\"wangwu\",\"33\":\"maliu\"}}";
// JSONArray.parse()
System.out.println(json);
}
}
package com.wanggs.com.wanggs.json.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
/**
* Created by wanggs on 2017/7/27.
*/
public class FastJsonTest {
public static void main(String[] args) {
String json = "[{\"id\":1,\"type\":\"cycle\",\"attribute\":{\"center\":\"(10.4, 123.345)\", \"radius\":67.4}},{\"id\":2,\"type\":\"polygon\",\"attribute\":[{\"vertex\":\"(10.4, 133.345)\"}, {\"vertex\":\"(10.4, 143.345)\"}]}]";
JSONArray array = JSON.parseArray(json);
System.out.println(array.getJSONObject(0).getJSONObject("attribute").get("center"));
System.out.println(array.getJSONObject(1).getJSONArray("attribute").getJSONObject(1).get("vertex"));
// 输出结果为: (10.4, 123.345) (10.4, 143.345)
}
}
方法总结
java和js中JSONObject,JSONArray,Map,String之间转换——持续更新中
4.JSONObject、JSONArray,Map转String
JSONObject——String:
System.out.println(myJsonObject);//可直接输出JSONObject的内容
myJsonObject.toString();
JSONArray——String:
System.out.println(myJsonArray);//可直接输出myJsonArray的内容
myJsonArray.toString();
Map——String:
System.out.println(map);//可直接输出map的内容
map.toString();
5.Map转JSONArray
JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(map));
JSONObject myJson = JSONObject.fromObject(jsonString);
Map m = myJson;
7.JSONArray转JSONObject
for(int i=0 ; i < myJsonArray.length() ;i++)
{
//获取每一个JsonObject对象
JSONObject myjObject = myJsonArray.getJSONObject(i);
}
8.JSONArray转Map
9.Map转JSONObject
JSONObject json = JSONObject.fromObject( map );
10.Map转JSONArray
JSONArray.fromObject(map);
11.List转JSONArray
JSONArray jsonArray2 = JSONArray.fromObject( list );
JSON解析之FastJSON
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
public class JsonTool {
public static T getPerson(String jsonstring, Class cls) {
T t = null;
try {
t = JSON.parseObject(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
public static List getPersonList(String jsonstring, Class cls) {
List list = new ArrayList();
try {
list = JSON.parseArray(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> getPersonListMap1(
String jsonstring) {
List> list = new ArrayList>();
try {
list = JSON.parseObject(jsonstring,
new TypeReference>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
解析JSON
import com.google.gson.Gson;
public class JsonUtils {
public static String createJsonObject(Object obj) {
Gson gson = new Gson();
String str = gson.toJson(obj);
return str;
}
}
二、解析JSON
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
;
public class GsonTools {
public GsonTools() {
// TODO Auto-generated constructor stub
}
/**
* @param
* @param jsonString
* @param cls
* @return
*/
public static T getPerson(String jsonString, Class cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
/**
* 使用Gson进行解析 List
*
* @param
* @param jsonString
* @param cls
* @return
*/
public static List getPersons(String jsonString, Class cls) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
}
return list;
}
/**
* @param jsonString
* @return
*/
public static List getList(String jsonString) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> listKeyMaps(String jsonString) {
List> list = new ArrayList>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString,
new TypeToken>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
2、解析JSON字符串
分为以下三种情况,一个JavaBean,一个List数组,一个嵌套Map的List数组:
生成json字符串
public static String createJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
解析
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.myjson.domain.Person;
/**
* 完成对json数据的解析
*
*/
public class JsonTools {
public static Person getPerson(String key, String jsonString) {
Person person = new Person();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject personObject = jsonObject.getJSONObject("person");
person.setId(personObject.getInt("id"));
person.setName(personObject.getString("name"));
person.setAddress(personObject.getString("address"));
} catch (Exception e) {
// TODO: handle exception
}
return person;
}
public static List getPersons(String key, String jsonString) {
List list = new ArrayList();
try {
JSONObject jsonObject = new JSONObject(jsonString);
// 返回json的数组
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Person person = new Person();
person.setId(jsonObject2.getInt("id"));
person.setName(jsonObject2.getString("name"));
person.setAddress(jsonObject2.getString("address"));
list.add(person);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List getList(String key, String jsonString) {
List list = new ArrayList();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
String msg = jsonArray.getString(i);
list.add(msg);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> listKeyMaps(String key,
String jsonString) {
List> list = new ArrayList>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map map = new HashMap();
Iterator iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String json_key = iterator.next();
Object json_value = jsonObject2.get(json_key);
if (json_value == null) {
json_value = "";
}
map.put(json_key, json_value);
}
list.add(map);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}