Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON GSON.fromJson Java Objects

Tags:

java

json

gson

I am trying to load my Json into my class

public User() {     this.fbId = 0;     this.email = "";     this.name = "";     this.thumb = "";     this.gender = "";     this.location = "";     this.relationship = null;     this.friends = new ArrayList(); } 
{     users:{         user:{             name:'the name',             email:'[email protected]',             friends:{                 user:{                     name:'another name',                     email:'[email protected]',                     friends:{                         user:{                             name:'yet another name',                             email:'[email protected]'                         }                     }                 }             }         }     } } 

I am struggling to get GSON to load the user details into the above Java object with the following code

User user = gson.fromJson(this.json, User.class); 
like image 251
Deviland Avatar asked Mar 15 '11 16:03

Deviland


People also ask

How do you serialize and deserialize JSON object in Java?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

What is difference between fromJson and toJson?

There are two parameters in the fromJson() method, the first parameter is JSON String which we want to parse and the second parameter is Java class to parse JSON string. We can pass one parameter into the toJson() method is the Java object which we want to convert into a JSON string.


1 Answers

The JSON is invalid. A collection is not to be represented by {}. It stands for an object. A collection/array is to be represented by [] with commaseparated objects.

Here's how the JSON should look like:

{     users:[{         name: "name1",         email: "email1",         friends:[{             name: "name2",             email: "email2",             friends:[{                 name: "name3",                 email: "email3"             },             {                 name: "name4",                 email: "email4"             }]         }]     }] } 

(note that I added one more friend to the deepest nested friend, so that you understand how to specify multiple objects in a collection)

Given this JSON, your wrapper class should look like this:

public class Data {     private List<User> users;     // +getters/setters }  public class User {     private String name;     private String email;     private List<User> friends;     // +getters/setters } 

and then to convert it, use

Data data = gson.fromJson(this.json, Data.class); 

and to get the users, use

List<User> users = data.getUsers(); 
like image 189
BalusC Avatar answered Oct 21 '22 03:10

BalusC