jasonzue / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Feature: Add support for InstanceCreatorEx interface with createInstance(JsonElement json, Type typeOfT) #238

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
json data can contain information about which exact class should be created,
but original InstanceCreator can't use this information.

Example: 
I have abstract Command class and Command1, Command2, etc subclasses.
My json data contains "type":"Command1" pair.

So we can overcome "Collections Limitations" and can deserialize 

Collection[? extends Command] realCommands = gson.fromJson(json, 
collectionTypeCommand);

Original issue reported on code.google.com by rybin.andrey on 20 Sep 2010 at 12:38

GoogleCodeExporter commented 9 years ago
This issues isn't about collections, it's about being able to deserialize a 
derived type, when only the base type is known:

IMyInterface deserialized = gson.fromJson(json, IMyInterface.class);

It would seem that the JSON itself would need some type identifier to know 
which derived type to use.

Original comment by MarceliN...@gmail.com on 5 Oct 2010 at 3:58

GoogleCodeExporter commented 9 years ago
In my case I have this identifier.
One field inside json contains "type" of this object.
And I want to use this "type" to create subclass of "IMyInterface".

Original comment by rybin.andrey on 5 Oct 2010 at 7:46

GoogleCodeExporter commented 9 years ago
Another example (as XStream does)

import java.io.*;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.xml.XppReader;

public class Test{
    public static void main(String[] args) {
        String xml = "<user>" +

                        "<name>Pavel</name>" +

                        "<sername>Samolisov</sername>" +

                        "<age>23</age>" +

                        "<rating>89.93</rating>" +

                     "</user>";

       StringWriter buffer = new StringWriter();
        HierarchicalStreamReader reader = new XppReader(new StringReader(xml));

        HierarchicalStreamWriter writer = new JettisonMappedXmlDriver().createWriter(buffer);
        HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
        copier.copy(reader, writer);
        System.out.println(buffer);
    }
}

Result: 
{"user":{"name":"Pavel","sername":"Samolisov","age":"23","rating":"89.93"}}

So every object has "root"

Original comment by rybin.andrey on 6 Oct 2010 at 8:38

GoogleCodeExporter commented 9 years ago

Original comment by limpbizkit on 6 Oct 2010 at 5:57