What serialization library should I use?

I would like to serialize specific fields for an object. And during the deserialization process, forcibly rebuild the object by going through the corresponding constructor. Is it possible?

Example:

public Person()
{
    private String name;
    private int age;
    private Person parent;

    void Person(String name, int age)
    {
        this.name = name;
        this.age = age;

        this.parent = new Person("Mom", 65);
    }
}

I would like to keep the "name" and "age" fields of the person. And during deserialization, to invoke the constructor and recreate the parent object.

+3
source share
3 answers

xstream supports the use of non-standard constructors in advanced mode.

http://x-stream.imtqy.com/index.html

+1
source

Person , Serializable, Java. .

, .

article Java.

0

, Gson JSON . Gson , , - , . , , , , , .

, , :

public class Person {
  private String name;
  private int age;
  private Person parent = null;

  public Person() {
    // Required no-args constructor for Gson.
  }

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

Person joe = new Person("Joe", 20);
Gson gson = new Gson();
String json = gson.toJson(joe);  
==> json is {"name":"Joe","age":"20"}

, , . , , , , .

Person joe = gson.fromJson(json, Person.class);

- , , . :

- , . (DateTime ..). Gson . : Json Serialiers: Json Deserializers: Instance Creators: no-args

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());

The registerTypeAdapter call checks to see if an adapter of type implements more than one of these interfaces and register it for all of them.

Writing a serializer

Here is an example of how to write a custom serializer for the JodaTime DateTime class.

private class DateTimeSerializer implements JsonSerializer<DateTime> {
  public JsonElement serialize(DateTime src, Type typeOfSrc,
      JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());
  }
}

Gson calls toJson () when it launches a DateTime object during serialization.

Writing a Deserializer

Here is an example of how to write a custom deserializer for the JodaTime DateTime class.

private class DateTimeDeserializer implements
    JsonDeserializer<DateTime> {
  public DateTime deserialize(JsonElement
      json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return new DateTime(json.getAsJsonPrimitive().getAsString());
  }
}

Gson calls fromJson () when it needs to deserialize a fragment of a JSON string into a DateTime object

0
source

All Articles