com.mycomm.itool.json.JsonParser Maven / Gradle / Ivy
package com.mycomm.itool.json;
/**
* Created by jw362j on 7/30/2014.
*/
import com.mycomm.itool.SystemUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class JsonParser {
/**
* Parse a String to a JsonValue.
*
* @param s
* a String
* @return a JsonValue
*/
public static JsonValue parse(String s) {
return JsonValue.parseValue(s);
}
public static void serialize(JsonValue obj, DataOutputStream dos) throws IOException {
JsonValue.writeObject(obj, dos);
}
/**
* serialize the object
*
* @param obj
* the object which is serialized
* @param gzip
* using gzip compress
* @return
* @throws IOException
*/
public static byte[] serialize(JsonValue obj, boolean gzip) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = null;
if (gzip) {
GZIPOutputStream gos = new GZIPOutputStream(baos);
dos = new DataOutputStream(gos);
} else {
dos = new DataOutputStream(baos);
}
serialize(obj, dos);
dos.close();
return baos.toByteArray();
}
public static JsonValue deserialize(DataInputStream dis) throws IOException {
JsonValue obj = JsonValue.readObject(dis);
try {
while (dis.read() != -1)
;
} catch (IOException e) {
}
return obj;
}
/**
* unserialize the object
*
* @param bytes
* target data
* @param gzip
* using gzip or not
* @return Structured data
* @throws IOException
*/
public static JsonValue deserialize(byte[] bytes, boolean gzip) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = null;
if (gzip) {
GZIPInputStream gis = new GZIPInputStream(bais);
dis = new DataInputStream(gis);
} else {
dis = new DataInputStream(bais);
}
JsonValue obj = deserialize(dis);
dis.close();
return obj;
}
}