How to convert a list of objects to a JSON object?

I have a HashSet of objects that I am trying to put on a JSON object.

HashSet<Users> users; 

...

JSONObject j = new JSONObject();
    j.put("users", users);

However,

System.out.println(j.toString(2));        

is giving me

{"users": [
  {},
  {}
]}

when there are 2 entries in the HashSet. The non-null values of Users objects are not there.

Is there more to converting a List of a declared type to a JSONObject?

I am using the JSON at org.json.*.

The Users class is as follows:

public class Users {
    byte[] pic;
    String firstName;
    String lastName;
    String address;
}

I'm seeing the entries in the HashSet "users" fine every otherwise.

TIA.

Jon Skeet
people
quotationmark

The problem is with your Users class. You appear to be expecting it to just pick up the fields, but I don't believe JSONObject does that - instead, it finds bean-like getters.

If you try to convert a single instance of your Users class to a JSONObject you get exactly the same result ({}) - this problem has nothing to do with trying to convert multiple instances. (It would be worth taking a lesson from this about diagnosing problems - always try to reduce the scope.)

As soon as you create a class with appropriate getters, it works fine. Sample code:

public final class User {
    private final String firstName;
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

import org.json.*;
import java.util.*;

class Test {
   public static void main(String [] args) throws Exception {
       User user = new User("Jon", "Skeet");
       JSONObject single = new JSONObject(user);
       System.out.println("Single user: " + single);

       Set<User> users = new HashSet<>();
       users.add(new User("Jon", "Skeet"));
       users.add(new User("Holly", "Skeet"));

       JSONObject multiple = new JSONObject();
       multiple.put("users", users);
       System.out.println("Multiple users: " + multiple);
   }
}

Output:

Single user: {"lastName":"Skeet","firstName":"Jon"}
Multiple users: {"users":[{"lastName":"Skeet","firstName":"Holly"},{"lastName":"Skeet","firstName":"Jon"}]}

people

See more on this question at Stackoverflow