2015-01-15 21:35:35 +00:00
|
|
|
package org.thoughtcrime.securesms.util;
|
|
|
|
|
|
|
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
2018-04-27 00:03:54 +00:00
|
|
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
2015-01-15 21:35:35 +00:00
|
|
|
|
2018-02-07 22:01:37 +00:00
|
|
|
import org.json.JSONException;
|
|
|
|
import org.json.JSONObject;
|
|
|
|
|
2015-01-15 21:35:35 +00:00
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.InputStream;
|
|
|
|
import java.io.InputStreamReader;
|
2016-10-17 02:05:07 +00:00
|
|
|
import java.io.Reader;
|
2015-01-15 21:35:35 +00:00
|
|
|
|
|
|
|
public class JsonUtils {
|
|
|
|
|
|
|
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
|
|
|
static {
|
|
|
|
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
2018-04-27 00:03:54 +00:00
|
|
|
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
|
|
|
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
2015-01-15 21:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-10-02 18:42:24 +00:00
|
|
|
public static <T> T fromJson(byte[] serialized, Class<T> clazz) throws IOException {
|
|
|
|
return fromJson(new String(serialized), clazz);
|
|
|
|
}
|
|
|
|
|
2015-01-15 21:35:35 +00:00
|
|
|
public static <T> T fromJson(String serialized, Class<T> clazz) throws IOException {
|
|
|
|
return objectMapper.readValue(serialized, clazz);
|
|
|
|
}
|
|
|
|
|
2016-10-17 02:05:07 +00:00
|
|
|
public static <T> T fromJson(InputStream serialized, Class<T> clazz) throws IOException {
|
|
|
|
return objectMapper.readValue(serialized, clazz);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static <T> T fromJson(Reader serialized, Class<T> clazz) throws IOException {
|
2015-01-15 21:35:35 +00:00
|
|
|
return objectMapper.readValue(serialized, clazz);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static String toJson(Object object) throws IOException {
|
|
|
|
return objectMapper.writeValueAsString(object);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static ObjectMapper getMapper() {
|
|
|
|
return objectMapper;
|
|
|
|
}
|
2018-02-07 22:01:37 +00:00
|
|
|
|
|
|
|
public static class SaneJSONObject {
|
|
|
|
|
|
|
|
private final JSONObject delegate;
|
|
|
|
|
|
|
|
public SaneJSONObject(JSONObject delegate) {
|
|
|
|
this.delegate = delegate;
|
|
|
|
}
|
|
|
|
|
|
|
|
public String getString(String name) throws JSONException {
|
|
|
|
if (delegate.isNull(name)) return null;
|
|
|
|
else return delegate.getString(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
public long getLong(String name) throws JSONException {
|
|
|
|
return delegate.getLong(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
public boolean isNull(String name) {
|
|
|
|
return delegate.isNull(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
public int getInt(String name) throws JSONException {
|
|
|
|
return delegate.getInt(name);
|
|
|
|
}
|
|
|
|
}
|
2015-01-15 21:35:35 +00:00
|
|
|
}
|