Serialize/deserialize IDL data structures with JSON

2 posts / 0 new
Last post
Offline
Last seen: 4 years 9 months ago
Joined: 01/09/2013
Posts: 10
Serialize/deserialize IDL data structures with JSON

Hi,

I would like to serialize and deserialize data exchanged through DDS with JSON. I found in a document from Gerardo Pardo that let me hope it is easily feasible (http://www.omg.org/news/meetings/GOV-WS/pr/rte-pres/DDS_WebEnabled_RTEW09.pdf).

After generating the Java class from the IDL description, I succeeds in serializing it into JSON format. The deserialization seems more difficult, perhaps due to the use of sequences and embedded substructures.

Do you have examples of Java code to do such a deserialization?

Thanks in advance.

JavierPovedano's picture
Offline
Last seen: 1 year 3 weeks ago
Joined: 06/05/2013
Posts: 16

Hi,

The types generated by rtiddsgen are standard java classes, so it can be easily serialized/serialized using any third party library that does that. One good example is Google Gson library. This library provides JSON serializers/deserializers to Java objects that can be easily incorporated in your code.

Imagine you have this idl definition:

struct Inner {
        long id;
};

struct MyHello{
        string<256> mystring;
        long mylong;
        sequence<double,10> myseq;
        Inner myinner;
};

Here it is a snippet of how it can be serialized/deserialize using Google Gson:

instance.mystring = "String " + count;
instance.mylong = count;
 

instance.myseq.setMaximum(0);
for(int i=0;i< 10;++i){
instance.myseq.add((double)count);
}

instance.myinner.id = count;

System.out.println("Original " + instance.toString());
/* Modify the instance to be written here */
System.out.println("Serialized : " + gson.toJson(instance));

String serialized = gson.toJson(instance);

MyHello deserialized = gson.fromJson(serialized,MyHello.class);

System.out.println("\nDeserialized " + deserialized.toString());   

The output for this program will be: 

 Original :
    mystring: String 1
    mylong: 1
    myseq: 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    myinner :
        id: 1

Serialized : {"mystring":"String 1","mylong":1,"myseq":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"myinner":{"id":1}}

Deserialized :
    mystring: String 1
    mylong: 1
    myseq: 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    myinner :
        id: 1

 

Note that might be necessary to build your custom serializer/deserializers for certain data types or complex structures.

Let me know if you have further questions,

- Javier