Read specific field from ObjectReader

15 views
Skip to first unread message

张鹏鹏

unread,
Sep 6, 2016, 12:45:50 PM9/6/16
to Genson user group
I'm working on Ser/De geojson use Genson.

So,I have Genson as base class and Feature(and a lot of others) as derived class.

I create a Deserializer with Genson Generic.

public class GeoJSONSerializer implements Deserializer<GeoJSON> {
 
@Override
   public GeoJSON deserialize(ObjectReader reader, Context ctx) throws Exception {
     
Map<String,Object> properties = new HashMap<>();
      GeoJSON geoJSON = null;
      reader
.beginObject();
      while (reader.hasNext()) {
         reader
.next();
         
switch (reader.name()) {
           
case "type":
              geoJSON
= createGeoJson(reader.valueAsString());
             
break;
           
case "properties":
              properties
.put("properties",ctx.genson.deserialize(new GenericType<JsonObject>(){}, reader, ctx));
             
break;
           
default:
             reader
.skipValue();
         
}
     
}
     reader
.endObject();

     if(geoJSON != null) {
         
//set values

       
}
     return geoJSON;
  }
}

I want to return Polymorphic types from the deserialize method.I must instantiate object corresponding the value of 'type' in the Geojson.



Now I have a map to save all the values,and at last after I know the exactly type I do the assignment work.But in that way I will lost the benefit of Streaming.

How can I do that?
Can I use xpath in the ObjectReader or do some Sorting operation  before deserialize?




eugen

unread,
Nov 17, 2016, 5:40:33 PM11/17/16
to Genson user group
Hi,

Sorry for not answering before, I don't know why but I never got this message in my mail box...

No there is no Xpath or sorting etc, as in order to do this Genson would need to keep in memory the structure (so basically we would loose the advantage of streaming).

Do you know that Genson provides a feature to do something similar to what you are doing here (useClassMetadata)? Maybe you could use it instead.
However this would be enabled for every type not only GeoJSON.
In Genson this mechanism is implemented by having as first property in the stream the type.
If you want you can implement something similar, have a look at how ClassMetadataConverter. But the constraint will be that the property must appear before any other property and must be prefixed by @ (if not generated by Genson).

Let me know if you need more guidance on how to achieve that.

Cheers,
Eugen
Reply all
Reply to author
Forward
0 new messages