1

I'm trying to convert a list of objects into json but the values are the location in memory.

public class User {

private String name;
private int score;

public User(String name, int score){
    this.name = name;
    this.score = score;
}

User user1= new User("Luke", 50);
User user2 = new User("Ryan", 70);
List<User> list = Arrays.asList(user1, user2);
Gson gson = new Gson(); 
String json = gson.toJson(list);  
System.out.println(list);

The last line is supposed to show my objects in json but instead i just get [User@579bb367, User@1de0aca6], why is this? thanks

LC12382
  • 97
  • 2
  • 10

4 Answers4

3

You meant

System.out.println(json);

What you did was to print the List, that, without a toString, will just print a default hash

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
0

You just print the hashcode of the list. When you call System.out.println() method, it will call toString() method of List. It is

getClass().getName() + '@' + Integer.toHexString(hashCode())

Adam Lyu
  • 431
  • 1
  • 5
  • 17
0

You need to implement a toString() method for the Object inside your list, or you will get the hash codes.

daniel.keresztes
  • 875
  • 2
  • 15
  • 25
0

When you print a list, you're in fact (implicitly) calling its toString() method, which usually just calls each of its element's toString()s, concatinates them with commas and encloses them in brackets. If your User class does not override toString() it will use Object's implementation that just prints the class' simple name and its default hashCode(), which is typically the memory address. If you want something more intelligent there, you'd have to override toString(). E.g.:

@Override
public String toString() {
    return String.format("[User name %s, score %d]", name, score);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350