1

I have a Class Graph having two ArrayLists as member variables and I would like to convert it into a JSON file using the GSON library.

This is the code of the class Graph :

public class Graph {

    private List<Node> nodes;
    private List<Link> links;

    // Constructors, Getters and Setters


}

This is the code of the class Node :

public class Node {

    private String name;
    private int group;

    // Constructors, Getters and Setters


}

This is the code of the class Link :

public class Link {

    private int source;
    private int target;

    // Constructors, Getters and Setters


}

This is the JSON file I would like to generate :

{
  "nodes":[
    {"name":"Myriel","group":1},
    {"name":"Napoleon","group":1},
    {"name":"Mlle.Baptistine","group":2},
    {"name":"Mme.Hucheloup","group":2}
  ],
  "links":[
    {"source":1,"target":0},
    {"source":2,"target":0},
    {"source":3,"target":1},
    {"source":3,"target":2}
  ]
}

This is the Main class :

public class Main {

    public static void main(String[] args) throws IOException {

        Graph graph = new Graph();

        List<Node> nodes = new ArrayList<Node>();
        nodes = DAO.listNodes();    //This function fills the list from a database

        List<Link> links = new ArrayList<Link>();
        links = DAO.listLinks();    //This function fills the list from a database

        graph.setNodes(nodes);
        graph.setLinks(links);

        Writer writer = new FileWriter("output.json");

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        gson.toJson(graph, writer);

        writer.close();

    }

}

And this is the error I get :

Exception in thread "main" java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:68)
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ArrayTypeAdapter.write(ArrayTypeAdapter.java:93)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:91)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:206)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:91)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:206)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:91)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:206)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:91)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:206)
    at com.google.gson.Gson.toJson(Gson.java:595)
    at com.google.gson.Gson.toJson(Gson.java:574)
    at com.google.gson.Gson.toJson(Gson.java:549)
    at gson.Main.main(Main.java:36)

What is the problem? And how can I fix it?

user1885868
  • 983
  • 2
  • 14
  • 29
  • 1
    possible duplicate of [Could not serialize object cause of HibernateProxy](http://stackoverflow.com/questions/13459718/could-not-serialize-object-cause-of-hibernateproxy) – andersschuller Aug 25 '14 at 11:02
  • @andersschuller I already saw that topic and it wasn't clear enough. – user1885868 Aug 25 '14 at 11:04
  • You haven't got any ArrayLists. You create two ArrayLists, but then you throw them away by replacing them with the return values of DAO.listNodes/Links. – Boann Aug 25 '14 at 11:26
  • @Boann could you explain more? – user1885868 Aug 25 '14 at 12:09
  • @user1885868 This assignment to `nodes` doesn't do anything: `= new ArrayList()`, because on the next line, you reassign it with `= DAO.listNodes()`. – Boann Aug 25 '14 at 12:14
  • @Boann Now I see! Thanks! But I still get that the same error message, looks like it has to do with some `HibernateProxy` thing : `Exception in thread "main" java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?` – user1885868 Aug 25 '14 at 12:29
  • @user1885868 I believe the problem is that the elements returned by your DAO calls are `HibernateProxy` objects. Did you try to register the custom TypeAdapter included in the answer to the linked question? – andersschuller Aug 25 '14 at 14:57
  • @andersschuller I just did but it gives me this error message : `Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session` What is that? – user1885868 Aug 25 '14 at 15:47

3 Answers3

1

I found a solution :

GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Node.class, new NodeAdapter()).registerTypeAdapter(Link.class, new LinkAdapter());
        Gson gson = gsonBuilder.create();
        writer.write(gson.toJson(graph)); 

It did generate a JSON file the way I wanted it.

Thanks for your help!

This is the LinkAdapter class :

public class LinkAdapter implements JsonSerializer<Link> {

    public JsonElement serialize(Link link, Type type,
            JsonSerializationContext jsc) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("source", link.getNodeBySource().getIdNode());
        jsonObject.addProperty("target", link.getNodeByTarget().getIdNode());

        return jsonObject;
    }

}

And this is the NodeAdapter class :

public class NodeAdapter implements JsonSerializer<Node> {

    public JsonElement serialize(Node node, Type type,
            JsonSerializationContext jsc) {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", node.getName());
        jsonObject.addProperty("group", node.getHyperEdge().getIdHe());

        return jsonObject;
    }


}
user1885868
  • 983
  • 2
  • 14
  • 29
0

Do this to pull the elements out of the proxy lists into the ArrayLists:

List<Node> nodes = new ArrayList<Node>();
nodes.addAll(DAO.listNodes());

List<Link> links = new ArrayList<Link>();
links.addAll(DAO.listLinks());
Boann
  • 44,932
  • 13
  • 106
  • 138
-1

First get JSON string from gson and then write it into file.

    Graph graph = new Graph()
    //This function fills the list from a database
    List<Node> nodes = DAO.listNodes();   
    //This function fills the list from a database
    List<Link> links = DAO.listLinks();    

    graph.setNodes(nodes);
    graph.setLinks(links);

    File file = new File("output.json");
    // creates the file
    file.createNewFile();
    // creates a FileWriter Object
    FileWriter writer = new FileWriter(file); 
    // Write JSON content to the file
    writer.write(gson.toJson(graph)); 
    writer.flush();
    writer.close();

Thank you

Oomph Fortuity
  • 4,952
  • 10
  • 35
  • 85