Skip to content

Instantly share code, notes, and snippets.

@zebulon988
Last active December 24, 2016 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zebulon988/999590979ec4d809165e0b272113b9f1 to your computer and use it in GitHub Desktop.
Save zebulon988/999590979ec4d809165e0b272113b9f1 to your computer and use it in GitHub Desktop.
FastJson serialize and deserialize org.json.JSONObject and org.json.JSONArray
package zebulon.test.zebulon.test.fastjson;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ListSerializer;
import com.alibaba.fastjson.serializer.MapSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import zebulon.test.BuildConfig;
/**
* Created by lize on 2016/12/24.
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class , sdk = 23)
public class JavaJsonObjectDeserializerTest {
public static class AndroidJsonObjectSerializer implements ObjectSerializer {
private MapSerializer mapSerializer = new MapSerializer();
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
if (object == null) {
serializer.out.writeNull();
return;
}
org.json.JSONObject jsonObject = (org.json.JSONObject) object;
if(object != null){
Map<String , Object> map = json2Map(jsonObject);
TypeReference typeReference = new TypeReference<Map<String , Object>>(){};
mapSerializer.write(serializer,map,fieldName,typeReference.getType());
}
}
Map<String , Object> json2Map(org.json.JSONObject jsonObject){
if(jsonObject == null) return null;
Map<String , Object> result = new HashMap<>();
Iterator<String> stringIterator = jsonObject.keys();
while (stringIterator.hasNext()){
String key = stringIterator.next();
Object value = jsonObject.opt(key);
if(value != null && value != JSONObject.NULL){
result.put(key,value);
}
}
return result;
}
}
public static class AndroidJsonObjectDeserializer implements ObjectDeserializer {
@Override
public org.json.JSONObject deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
String str = parser.parseObject(String.class);
if (TextUtils.isEmpty(str)) {
return null;
} else {
try {
return new org.json.JSONObject(str);
} catch (JSONException e) {
throw new IllegalStateException(e);
}
}
}
}
public static class AndroidJsonArraySerializer implements ObjectSerializer{
ListSerializer listSerializer = new ListSerializer();
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
if (object == null) {
serializer.out.writeNull();
return;
}
JSONArray jsonArray = (JSONArray) object;
List<Object> list = new ArrayList<>();
for(int i = 0 ; i < jsonArray.length() ; ++i){
Object item = jsonArray.opt(i);
if(item == null || item == JSONObject.NULL){
}else{
list.add(item);
}
}
TypeReference typeReference = new TypeReference<ArrayList<Object>>(){};
listSerializer.write(serializer , list , fieldName , typeReference.getType());
}
}
public static class AndroidJsonArrayDeserializer implements ObjectDeserializer{
@Override
public JSONArray deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
String str = parser.parseObject(String.class);
if (TextUtils.isEmpty(str)) {
return null;
} else {
try {
return new org.json.JSONArray(str);
} catch (JSONException e) {
throw new IllegalStateException(e);
}
}
}
}
@After
public void tearDown() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONObject.class, null);
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONObject.class,null);
SerializeConfig.getGlobalInstance().put(org.json.JSONArray.class, null);
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONArray.class,null);
}
@Test
public void testSerializerAndroidJsonObject() throws Exception {
org.json.JSONObject element = new org.json.JSONObject();
element.put("a","a");
Assert.assertNotEquals(element.toString() , JSON.toJSONString(element));
//Expected :{"a":"a"}
//Actual :{}
}
@Test
public void testSerializerAndroidJsonObjectWithCustomSerializer() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONObject.class, new AndroidJsonObjectSerializer());
org.json.JSONObject element = new org.json.JSONObject();
element.put("a","a");
Assert.assertEquals(element.toString() , JSON.toJSONString(element));
}
@Test
public void testDeserializerAndroidJsonObject() throws Exception {
org.json.JSONObject element = new org.json.JSONObject();
element.put("a","a");
org.json.JSONObject androidJson = JSON.parseObject(element.toString() , org.json.JSONObject.class);
Assert.assertNotEquals("a",androidJson.optString("a"));
}
@Test
public void testDeserializerAndroidJsonObjectWithCustomDeserializer() throws Exception {
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONObject.class , new AndroidJsonObjectDeserializer());
org.json.JSONObject element = new org.json.JSONObject();
element.put("a","a");
org.json.JSONObject androidJson = JSON.parseObject(element.toString() , org.json.JSONObject.class);
Assert.assertEquals("a",androidJson.optString("a"));
}
//嵌套类型
@Test
public void testSerializerProduct() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONObject.class, new AndroidJsonObjectSerializer());
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONObject.class , new AndroidJsonObjectDeserializer());
Product product = new Product();
org.json.JSONObject element = new org.json.JSONObject();
element.put("a","a");
product.setElement(element);
Product out = JSON.parseObject(JSON.toJSONString(product) , Product.class);
Assert.assertEquals("a" , out.getElement().optString("a"));
}
@Test
public void testSerializerProduct_elementIsNull() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONObject.class, new AndroidJsonObjectSerializer());
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONObject.class , new AndroidJsonObjectDeserializer());
Product product = new Product();
Product out = JSON.parseObject(JSON.toJSONString(product) , Product.class);
Assert.assertNull(out.getElement());
}
@Test
public void testArraySerializer() throws Exception {
JSONArray jsonArray = new JSONArray();
jsonArray.put("a");
Assert.assertNotEquals("[\"a\"]" ,JSON.toJSONString(jsonArray));
//Expected :["a"]
//Actual :{}
}
@Test
public void testArraySerializerWithCustomSerializer() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONArray.class, new AndroidJsonArraySerializer());
JSONArray jsonArray = new JSONArray();
jsonArray.put("a");
Assert.assertEquals("[\"a\"]" ,JSON.toJSONString(jsonArray));
}
@Test(expected = com.alibaba.fastjson.JSONException.class)
public void testArrayDeserializer() throws Exception {
JSONArray jsonArray = JSON.parseObject("[\"a\"]" , JSONArray.class);
// syntax error, expect {
// 想用fastJson 直接反序列化 org.json.JSONArray 看来是不行了。
// 直接反序列化列表,必须调用 JSON.parseArray(...),但是返回值只能是 fastjson jsonArray 或者 List
// 但是嵌套的org.json.JSONArray反序列化没问题。
}
@Test
public void testSerializerArrayProduct() throws Exception {
SerializeConfig.getGlobalInstance().put(org.json.JSONArray.class, new AndroidJsonArraySerializer());
JSONArray jsonArray = new JSONArray();
jsonArray.put("a");
ArrayProduct arrayProduct = new ArrayProduct();
arrayProduct.setArray(jsonArray);
Assert.assertEquals("{\"array\":[\"a\"]}" , JSON.toJSONString(arrayProduct));
}
@Test
public void testDeserializerArrayProduct() throws Exception {
ParserConfig.getGlobalInstance().putDeserializer(org.json.JSONArray.class, new AndroidJsonArrayDeserializer());
ArrayProduct arrayProduct = JSON.parseObject("{\"array\":[\"a\"]}" , ArrayProduct.class);
Assert.assertEquals("a" , arrayProduct.getArray().optString(0));
}
public static class Product{
private org.json.JSONObject element;
public org.json.JSONObject getElement() {
return element;
}
public void setElement(org.json.JSONObject element) {
this.element = element;
}
}
public static class ArrayProduct{
private org.json.JSONArray array;
public JSONArray getArray() {
return array;
}
public void setArray(JSONArray array) {
this.array = array;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment