I create class with methods like a How to serialize an object into a string
and it every say error "java.lang.ClassCastException: java.lang.String cannot be cast to Myclass"
My codes:
1)
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.xml.bind.DatatypeConverter;
public class Serialization {
public static Object fromString(String s) throws IOException,
ClassNotFoundException {
byte[] data = DatatypeConverter.parseBase64Binary(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
data));
Object o = ois.readObject();
ois.close();
return o;
}
public static String toString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return DatatypeConverter.printBase64Binary(baos.toByteArray());
}
}
2) - calling
MyClass hl = (MyClass) Serialization.fromString(items
.getString("data"));
hl.load(); // this is my method from class
3) MyClass - Hologram
public class Hologram implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Location loc;
private String name;
private String displayname;
public ArmorStand stand;
public Hologram(String name, String displayname, Location loc) {
this.loc = loc;
this.name = name;
this.displayname = displayname;
ArmorStand as = (ArmorStand) loc.getWorld().spawnEntity(loc,
EntityType.ARMOR_STAND);
as.setGravity(false);
as.setCanPickupItems(false);
as.setCustomName(displayname);
as.setCustomNameVisible(true);
as.setVisible(false);
this.stand = as;
HologramManager.holograms.put(name, this);
}
public void move(Location loc) {
this.loc = loc;
stand.teleport(loc);
}
public Location getLocation() {
return this.loc;
}
public void remove() {
stand.remove();
HologramManager.holograms.remove(name);
}
public void removeHologram() {
HologramManager.remove(name);
}
public void changeName(String name) {
HologramManager.holograms.remove(this.name);
this.name = name;
HologramManager.holograms.put(name, this);
}
public void changeDisplayName(String displayName) {
this.displayname = displayName;
stand.setCustomName(displayname);
stand.setCustomNameVisible(true);
}
public void load() {
//todo
}
}
Based on the linked answer, the problem most likely lies in the code you aren't showing us. When you serialize your MyClass object, you are probably doing something like this:
MyClass hl;
String base64String = Serialization.toString(hl.toString());
However you should be calling it like this:
MyClass hl;
String base64String = Serialization.toString(hl);
If you pass a String to the serialization function, you'll get a String back when you call Serialization.fromString(). You want to get an object back that you can cast to a MyClass instance, so pass one of those into Serialization.toString().
The fromString() method in Serilization returns an Object, which you wouldnt be able to cast to the class MyClass. The below line is causing the classCastException
MyClass hl = (MyClass) Serialization.fromString(items
.getString("data"));
Related
We have a class Agent with assignedUsers as List<Long>
when we try to convert the object as JSON document, we are using ObjectMapper writeValueAsString method, which does not serialize the ids into String instead the key assignedUsers are not missed in the JSON string.
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Agent {
private List<Long> assignedUserIds;
private String name;
private static final String json = "{\"name\":\"New Agency\", \"assignedUserIds\":[23,24]}";
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Long> gocuetAssignedUserIds() {
return assignedUserIds;
}
public void setAssignedUserIds(final List<Long> assignedUserIds) {
this.assignedUserIds = assignedUserIds;
}
public static void main(String[] args) {
Agent agencyInfo = null;
try {
agencyInfo = new ObjectMapper().readValue(json, Agent.class);
System.out.println("Built Agent :: " + new ObjectMapper().writeValueAsString(agencyInfo)); // Outputs: Built Agent :: {"name":"New Agency"}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your getter for the field assignedUserIds is called gocuetAssignedUserIds(). This is why it's not serialized (the mapper does not recognize it), either mark it with the annotiation #JsonGetter("assignedUserIds") or rename it to getAssignedUserIds() to match the field.
I am trying to save obj in files but java.io.NotSerializableException error doesnt allow me to do it.
This is my code:
import Estrategia.Gestor_nivel;
import Resources.Exceptions.DuplicateLevelsId;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import pp_epoca_normal.Gerir_jogo;
public class Teste {
public void guardar_ficheiro(Object obt) {
Gerir_jogo teste = (Gerir_jogo) obt;
System.out.println("sad---- " + teste);
Gestor_nivel sad;
try {
ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream("teste.dat"));
ObjectOutputStream objOut1 = new ObjectOutputStream(new FileOutputStream("teste1.dat"));
objOut.writeObject(teste);
objOut1.writeObject(teste.getObjetos());
sad = (Gestor_nivel) teste.getLevel(0);
objOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ler_ficheiro() throws FileNotFoundException, IOException, ClassNotFoundException, DuplicateLevelsId {
Gerir_jogo asd;
ObjectInputStream mySecondStream = new ObjectInputStream(new FileInputStream("teste.dat"));
ObjectInputStream mySecondStream1 = new ObjectInputStream(new FileInputStream("teste1.dat"));
asd = (Gerir_jogo) mySecondStream.readObject();
asd.setObjetos((Object[]) mySecondStream1.readObject());
System.out.println("leu--");
mySecondStream.close();
mySecondStream1.close();
}
}
Class gerir jogo
import Container.Contentor;
import Estrategia.Gestor_nivel;
import Resources.Exceptions.DuplicateLevelsId;
import Resources.GameContainerContract;
import Resources.GameLevelContract;
public class Gerir_jogo extends Contentor implements GameContainerContract {
private String nome_jogo;
private boolean mode_jogo_depuracao;
public Gerir_jogo(String nome_jogo, boolean mode_jogo) {
this.nome_jogo = nome_jogo;
this.mode_jogo_depuracao = mode_jogo;
}
#Override
public boolean addNewLevel(GameLevelContract glc) throws DuplicateLevelsId {
Gestor_nivel a;
boolean asd = false;
for (Object objetos : this.getObjetos()) {
a = (Gestor_nivel) objetos;
if(objetos != null)
if (a.getId() == glc.getId()) {
asd = true;
}
}
if (asd == false)
return super.addObject(glc);
return false;
}
#Override
public boolean removeLevel(GameLevelContract glc) {
return super.Encontrar_objeto(super.removeObject(super.findObject(glc)));
}
#Override
public GameLevelContract getLevel(int i) {
return (GameLevelContract) super.getObject(i);
}
#Override
public int getSize() {
return super.getCont();
}
#Override
public boolean getDebugMode() {
return this.mode_jogo_depuracao;
}
#Override
public void setDebugMode(boolean bln) {
this.mode_jogo_depuracao = bln;
}
#Override
public void setName(String string) {
this.nome_jogo = string;
}
#Override
public String getName() {
return this.nome_jogo;
}
Can someone help me please?
I really need to put this saving and reading files and what is inside them
Error:
java.io.NotSerializableException: pp_epoca_normal.Gerir_jogo
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at Gravar_ler_ficheiro.Teste.guardar_ficheiro(Teste.java:34)
at pp_epoca_normal.PP_epoca_normal.main(PP_epoca_normal.java:77)
I really dont know what to do
Your class Gerir_jogo must implements the interface Serializable. Please, take a look at this tutorial.
Edit 1
Your class does not implements it, so, change if for:
import java.io.Serializable;
public class Gerir_jogo extends Contentor implements GameContainerContract, Serializable {
Implement Serializable on Gerir_jogo class.
Change class declaration as:
import java.io.Serializable;
public class Gerir_jogo extends Contentor implements GameContainerContract, Serializable {
To serialize java object means to stream the byte information as non-static states of the object to external file. Here the class must be implemented by the interface "Serilizable".
Here I have replied with a code, which copies the States as id, name & sal of the class "Employee" to an external file present at the destination "D:\Object\States.txt". Here its not readable.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Employee implements Serializable {
int id;
String name;
double sal;
public Employee(int id, String name, double sal) {
super();
this.id = id;
this.name = name;
this.sal = sal;
}
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", sal=" + sal + "]";
}
public static void main(String[] args) throws Exception {
Employee e1 = new Employee(101, "Mr. S.V. Roshan", 45000.0D);
FileOutputStream fout = new FileOutputStream("D:/Object/State.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(e1);
out.flush();
out.close();
fout.flush();
fout.close();
System.out.println("Object serialized successfully!");
}
}
I think, It may help you..!
I would like to serialize a Java class on my MySQL database using Ebean ORM.
My class definition is similar to the following:
public class Test implements Serializable
{
#Id
private Long id;
...
...
...
#Lob
private MyClass1 obj1;
#Lob
private MyClass2 obj2;
...
...
//getters and setters
}
where my classes MyClass1 and MyClass2 are basically wrappers for a
float[]
and an
Hashmap<String, Float>
and both implement Serializable interface.
I don't want to have to create a class with:
#Lob
byte[] obj1bytes;
#Transient
MyClass1 obj1Obj;
#Lob
byte[] obj2bytes;
#Transient
MyClass2 obj2Obj;
//getters and setters
What I would like to obtain is serialize and deserialize this class automatically WITHOUT having to use byte[] arrays to hold obj1 and obj2 in my Test class to a MySQL table in two LongBlob fields using
Ebean.save(testClassInstance);
Ebean.find(Test.class, ID);
EDIT1: MyClass1 is defined as following:
public class MyClass1 implements Interface1 {
private float[] vector;
public MyClass1 () {
}
public MyClass1 (float[] vector) {
this.vector = vector;
}
public float[] getVector() {
return vector;
}
public void setVector(float[] vector) {
this.vector = vector;
}
#Override
public byte[] serialize() throws Exception {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(object);
out.close();
return byteOut.toByteArray();
}
#Override
public void deserialize(byte[] bytes) throws Exception {
ByteArrayInputStream byteInt = new ByteArrayInputStream(bytes);
ObjectInputStream out = new ObjectInputStream(byteInt);
vector = (float[])out.readObject();
}
#Override
public float cossim(MyClass1 v) throws Exception {
method logic
}
#Override
public MyClass1 add(MyClass1 v) throws Exception {
method logic
}
}
MyClass2 is defined as MyClass1, only that instead of float[] vector I have a HashMap < String, Float > (). The only differences worth noting are serialize() and deserialize():
#Override
public byte[] serialize() throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(outStream);
out.writeInt(map.size());
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
out.writeUTF(key);
out.writeFloat(map.get(key));
}
return outStream.toByteArray();
}
#Override
public void deserialize(byte[] bytes) throws Exception {
try {
ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(inStream);
this.map = new HashMap<>();
int n = in.readInt();
for (int i = 0; i < n; i++) {
map.put(in.readUTF(), in.readFloat());
}
} catch (Exception ex) {
throw ex;
}
}
Actually it is not necessary to wrap float[] and HashMap<String,float> as they themselves are serializable.
Another thing is that if MyClass1 and MyClass2 are serializable than you can use #Lob. According to this wikibook,
By default in JPA any Serializable attribute that is not a
relationship or a basic type (String, Number, temporal, primitive),
will be serialized to a BLOB field.
In that wikibook, there is also an example using #Lob for the class Image.
#Entity
public class Employee {
...
#Basic(fetch=FetchType.LAZY)
#Lob
private Image picture;
...
}
Hope this might help you.
I did some coding after your reply.
Condition: The fields of ClassB should be serializable and the fields of fields should be serializable and ....
ClassB:
import java.io.Serializable;
public class ClassB implements Serializable{
private static final long serialVersionUID = 1L;
String b;
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
ClassA:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
#Entity
public class ClassA implements Serializable{
private static final long serialVersionUID = 1L;
#Id
String a;
#Lob
ClassB b;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public ClassB getB() {
return b;
}
public void setB(ClassB b) {
this.b = b;
}
}
Here, ClassA contains ClassB object. You can add any logic in ClassB and it works. I have small problem with your overriding of serialize and deserialize. I think you do not need to do that. It will be done by default as it is serialized. And at last, these codes do work as I have tried it.
Hope this will help you.
I am trying to use GraphAdapterBuilder which is an extra to the GSON library to serialize an object with cyclic references. It works great for class but fails when trying to deserialize an interface.
To deserialize interface( which GSON doesn't do by default ) I am using PropertyBasedInterfaceMarshal or InterfaceAdapter. These are registered as custom type adapters for the interfaces.
When using ether above both fail to deserialize the interface as they are only passed the graph id like "0x4" as generated by GraphAdapterBuilder. This is passed as the JsonElement in the deserializer. Obviously there is nothing that can be done with this id from within the deserializer.
Shouldn't these be caught by the GraphAdapterBuilder instead of trying to be deserialized? I have not been able to get around this, is this a bug with GraphAdapterBuilder or is there a way to get around this?
Ok, this is a (working) stub for a solution. It's too late in Italy, to make it nicer.
You need a delegate function like this
package com.google.gson.graph;
/**
* #author Giacomo Tesio
*/
public interface GenericFunction<Domain, Codomain> {
Codomain map(Domain domain);
}
a TypeAdapterFactory like this:
package com.google.gson.graph;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* #author Giacomo Tesio
*/
public class InterfaceAdapterFactory implements TypeAdapterFactory {
final Map<String, GenericFunction<Gson, TypeAdapter<?>>> adapters;
private final Class<?> commonInterface;
public InterfaceAdapterFactory(Class<?> commonInterface, Class<?>[] concreteClasses)
{
this.commonInterface = commonInterface;
this.adapters = new HashMap<String, GenericFunction<Gson, TypeAdapter<?>>>();
final TypeAdapterFactory me = this;
for(int i = 0; i < concreteClasses.length; ++i)
{
final Class<?> clazz = concreteClasses[i];
this.adapters.put(clazz.getName(), new GenericFunction<Gson, TypeAdapter<?>>(){
public TypeAdapter<?> map(Gson gson) {
TypeToken<?> type = TypeToken.get(clazz);
return gson.getDelegateAdapter(me, type);
}
});
}
}
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
if(!this.commonInterface.isAssignableFrom(type.getRawType())
&& !this.commonInterface.equals(type.getRawType()))
{
return delegate;
}
final TypeToken<T> typeToken = type;
final Gson globalGson = gson;
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
out.beginObject();
out.name("#t");
out.value(value.getClass().getName());
out.name("#v");
delegate.write(out, value);
out.endObject();
}
#SuppressWarnings({"unchecked"})
public T read(JsonReader in) throws IOException {
JsonToken peekToken = in.peek();
if(peekToken == JsonToken.NULL) {
in.nextNull();
return null;
}
in.beginObject();
String dummy = in.nextName();
String typeName = in.nextString();
dummy = in.nextName();
TypeAdapter<?> specificDelegate = adapters.get(typeName).map(globalGson);
T result = (T)specificDelegate.read(in);
in.endObject();
return result;
}
};
}
}
a pair of tests like these
public final class InterfaceAdapterFactoryTest extends TestCase {
public void testInterfaceSerialization1(){
SampleInterface first = new SampleImplementation1(10);
SampleInterfaceContainer toSerialize = new SampleInterfaceContainer("container", first);
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(SampleInterfaceContainer.class)
.addType(SampleImplementation1.class)
.addType(SampleImplementation2.class)
.registerOn(gsonBuilder);
gsonBuilder.registerTypeAdapterFactory(new InterfaceAdapterFactory(
SampleInterface.class, new Class<?>[] { SampleImplementation1.class, SampleImplementation2.class }
));
Gson gson = gsonBuilder.create();
String json = gson.toJson(toSerialize);
System.out.println(json);
SampleInterfaceContainer deserialized = gson.fromJson(json, SampleInterfaceContainer.class);
assertNotNull(deserialized);
assertEquals(toSerialize.getName(), deserialized.getName());
assertEquals(toSerialize.getContent().getNumber(), deserialized.getContent().getNumber());
}
public void testInterfaceSerialization2(){
SampleImplementation2 first = new SampleImplementation2(5, "test");
SampleInterfaceContainer toSerialize = new SampleInterfaceContainer("container", first);
first.Container = toSerialize;
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(SampleInterfaceContainer.class)
.addType(SampleImplementation1.class)
.addType(SampleImplementation2.class)
.registerOn(gsonBuilder);
gsonBuilder.registerTypeAdapterFactory(new InterfaceAdapterFactory(
SampleInterface.class, new Class<?>[] { SampleImplementation1.class, SampleImplementation2.class }
));
Gson gson = gsonBuilder.create();
String json = gson.toJson(toSerialize);
System.out.println(json);
SampleInterfaceContainer deserialized = gson.fromJson(json, SampleInterfaceContainer.class);
assertNotNull(deserialized);
assertEquals(toSerialize.getName(), deserialized.getName());
assertEquals(5, deserialized.getContent().getNumber());
assertEquals("test", ((SampleImplementation2)deserialized.getContent()).getName());
assertSame(deserialized, ((SampleImplementation2)deserialized.getContent()).Container);
}
}
and some sample classes (to verify that the tests pass)
public class SampleInterfaceContainer {
private SampleInterface content;
private String name;
public SampleInterfaceContainer(String name, SampleInterface content)
{
this.name = name;
this.content = content;
}
public String getName()
{
return this.name;
}
public SampleInterface getContent()
{
return this.content;
}
}
public interface SampleInterface {
int getNumber();
}
public class SampleImplementation1 implements SampleInterface{
private int number;
public SampleImplementation1()
{
this.number = 0;
}
public SampleImplementation1(int number)
{
this.number = number;
}
public int getNumber()
{
return this.number;
}
}
public class SampleImplementation2 implements SampleInterface{
private int number;
private String name;
public SampleInterfaceContainer Container;
public SampleImplementation2()
{
this.number = 0;
this.name = "";
}
public SampleImplementation2(int number, String name)
{
this.number = number;
this.name = name;
}
public int getNumber()
{
return this.number;
}
public String getName()
{
return this.name;
}
}
While this has been a quick&dirty hack, it works like a charme.
You just have to pay attention at the order of the operations during the initialization of GsonBuilder. You have to initialize and register the GraphAdapterBuilder first and only after register this factory.
It has been funny (if a bit tricky since I'm not a Java expert).
I'm having some issues to deserialize a Json array that follows this format:
[
{
"ChildList":[
{
"ChildList":[
],
"Id":110,
"Name":"Books",
"ApplicationCount":0
}
],
"Id":110,
"Name":"Books",
"ApplicationCount":0
}
]
It's basically an array of Categories where each category can also have a List of sub-categories, and so on and so on.
My class model looks a little like this:
public class ArrayOfCategory{
protected List<Category> category;
}
public class Category{
protected ArrayOfCategory childList;
protected int id;
protected String name;
protected int applicationCount;
}
Now, Gson obviously complains about the circular reference. Is there any way to parse this Json input given that I can't assume how many levels of categories there are?
Thanks in advance.
Edit:
Just in case someone has a similar problem, based on Spaeth answer I adapted the solution to a more general case using reflection. The only requirement is that the List of objects represented by the JSON array is wrapped in another class (like Category and ArrayOfCategory in my example). With the following code applied to my original sample, you can just call "deserializeJson(jsonString,ArrayOfCategory.class)" and it will work as expected.
private <T> T deserializeJson(String stream, Class<T> clazz) throws PluginException {
try {
JsonElement je = new JsonParser().parse(stream);
if (je instanceof JsonArray) {
return deserializeJsonArray(clazz, je);
} else {
return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create().fromJson(stream, clazz);
}
} catch (Exception e) {
throw new PluginException("Failed to parse json string: " + ((stream.length() > 20) ? stream.substring(0, 20) : stream) + "... to class " + clazz.getName());
}
}
private <T> T deserializeJsonArray(Class<T> clazz, JsonElement je) throws InstantiationException, IllegalAccessException {
ParameterizedType listField = (ParameterizedType) clazz.getDeclaredFields()[0].getGenericType();
final Type listType = listField.getActualTypeArguments()[0];
T ret = clazz.newInstance();
final Field retField = ret.getClass().getDeclaredFields()[0];
retField.setAccessible(true);
retField.set(ret, getListFromJsonArray((JsonArray) je,(Class<?>) listType));
return ret;
}
private <E> List<E> getListFromJsonArray(JsonArray je, Class<E> listType) {
Type collectionType = new TypeToken<List<E>>(){}.getType();
final GsonBuilder builder = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
Gson jsonParser = builder.create();
return jsonParser.fromJson(je, collectionType);
}
Maybe you could try this:
com.google.gson.Gson gson = new GsonBuilder().create();
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("/tmp/gson.txt")));
Collection<Category> fromJson = gson.fromJson(reader, new TypeToken<Collection<Category>>() {}.getType());
System.out.println(fromJson);
you will get a good result.
The "magic" occurs here: new TypeToken<Collection<Category>>() {}.getType()
The entire code is:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.List;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
public class GsonCircularReference {
public class Category {
protected List<Category> childList;
protected int id;
protected String name;
protected int applicationCount;
public List<Category> getChildList() {
return childList;
}
public void setChildList(final List<Category> childList) {
this.childList = childList;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getApplicationCount() {
return applicationCount;
}
public void setApplicationCount(final int applicationCount) {
this.applicationCount = applicationCount;
}
#Override
public String toString() {
return "Category [category=" + childList + ", id=" + id + ", name=" + name + ", applicationCount="
+ applicationCount + "]";
}
}
public static void main(final String[] args) throws JsonSyntaxException, JsonIOException, FileNotFoundException {
com.google.gson.Gson gson = new GsonBuilder().create();
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("/tmp/gson.txt")));
Collection<Category> fromJson = gson.fromJson(reader, new TypeToken<Collection<Category>>() {}.getType());
System.out.println(fromJson);
}
}
JSON file is:
[
{
"childList":[
{
"childList":[
],
"id":110,
"Name":"Books",
"applicationCount":0
}
],
"id":110,
"name":"Books",
"applicationCount":0
}
]
Take a look at GraphAdapterBuilder. You'll need to include it in your app, but it can serialize arbitrary graphs of objects.