Post

2 followers Follow
0
Avatar

Joda DateTypes - Unable to convert PDXInstance to Json

Hi All,

I am using the JSONFormatter's toJSON method to convert a PDXInstance to Json but it's failing when it encounters a Joda datetime object. Please see the error below -

PdxInstance returns unknwon pdxfield inServiceDate for type Fri Jun 18 00:00:00 CDT 1971

Any advice?

Thanks

Arjun Reddy

Please sign in to leave a comment.

1 comment

0
Avatar

Unfortunately, JSONFormatter only currently supports simple data types. I wrote a couple sample classes you could use to serialize your PdxInstance to JSON.

I tested them with an PdxInstance containing a DateTime like:

  PdxInstance pdxInstance = ...;
  String json = JsonHelper.toJson(pdxInstance);

import com.gemstone.gemfire.pdx.PdxInstance;

import org.codehaus.jackson.*;

import org.codehaus.jackson.map.ObjectMapper;

import org.codehaus.jackson.map.module.SimpleModule;

import org.joda.time.DateTime;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

public class JsonHelper {

public static String toJson(PdxInstance pdxInstance) throws Exception {
JsonFactory jf = new JsonFactory();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator jg = jf.createJsonGenerator(baos, JsonEncoding.UTF8);
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
module.addSerializer(DateTime.class, new JodaDateTimeSerializer());
mapper.registerModule(module);
jg.setCodec(mapper);
jg.writeStartObject();
for (String fieldName : pdxInstance.getFieldNames()) {
Object value = pdxInstance.getField(fieldName);
System.out.println("Serializing value: " + value + " (an instance of " + value.getClass().getName() + ")");
jg.writeObjectField(fieldName, value);
}
jg.writeEndObject();
jg.close();
return baos.toString("UTF-8");
}
}

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;

import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import org.joda.time.DateTime;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.IOException;

public class JodaDateTimeSerializer extends JsonSerializer<DateTime> {

private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");

@Override
public void serialize(DateTime value, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));

}
}

Barry Oglesby 0 votes