org.dsa.iot.dslink.util.json.Json Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dslink Show documentation
Show all versions of dslink Show documentation
SDK for the IoT DSA protocol
package org.dsa.iot.dslink.util.json;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.json.UTF8JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import org.dsa.iot.dslink.node.value.Value;
import org.dsa.iot.dslink.node.value.ValueUtils;
import org.dsa.iot.dslink.util.UrlBase64;
import org.dsa.iot.dslink.util.json.decoders.ListDecoder;
import org.dsa.iot.dslink.util.json.decoders.MapDecoder;
import org.dsa.iot.dslink.util.json.encoders.ListEncoder;
import org.dsa.iot.dslink.util.json.encoders.MapEncoder;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
/**
* @author Samuel Grenier
*/
public class Json {
private static final MessagePackFactory MSG_FACTORY;
private static final JsonFactory JSON_FACTORY;
private Json() {
}
public static byte[] encode(EncodingFormat format,
Object obj) {
return performEncode(format, obj, null);
}
public static byte[] encodePrettily(EncodingFormat format,
Object obj) {
return performEncode(format, obj, new DefaultPrettyPrinter());
}
private static byte[] performEncode(EncodingFormat format,
Object obj,
PrettyPrinter printer) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonEncoding enc = JsonEncoding.UTF8;
JsonGenerator gen;
try {
if (format == EncodingFormat.JSON) {
gen = JSON_FACTORY.createGenerator(baos, enc);
} else if (format == EncodingFormat.MESSAGE_PACK) {
gen = MSG_FACTORY.createGenerator(baos, enc);
} else {
throw new UnsupportedOperationException(format.toJson());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
gen.setPrettyPrinter(printer);
if (obj instanceof JsonObject) {
MapEncoder.write(gen, (JsonObject) obj);
} else if (obj instanceof JsonArray) {
ListEncoder.write(gen, (JsonArray) obj);
}
gen.close();
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Map decodeMap(EncodingFormat format,
byte[] content,
int offset,
int length) {
if (format == EncodingFormat.JSON) {
return MapDecoder.decode(JSON_FACTORY, content, offset, length);
} else if (format == EncodingFormat.MESSAGE_PACK) {
return MapDecoder.decode(MSG_FACTORY, content, offset, length);
}
throw new UnsupportedOperationException(format.toJson());
}
public static List