简体   繁体   中英

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.

I got correct result using the code below. Can you highlight if you are doing something different? Maybe I can make similar changes and try once.

public static void main(String[] args){
    HashSet<String> users = new HashSet<>(); 
    users.add("user1");
    users.add("user2");

    JSONObject j = new JSONObject();
    j.put("users", users);
    System.out.println(j.toString(2));        
}

Output:

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

================================== EDIT =================================

I think I figured what the problem was. Please try the following code and let us know if that worked.

public static void main(String[] args) {
    JSONObject o1 = new JSONObject();
    o1.put("1", new User("User1"));
    JSONObject o2 = new JSONObject();
    o2.put("2", new User("User2"));

    HashSet<JSONObject> users = new HashSet<>(); 
    users.add(o1);
    users.add(o2);

    JSONObject j = new JSONObject();
    j.put("users", users);
    System.out.println(j.toString(2));        
}

Using gson, it is much simpler.

Use the following code snippet:

 // create a new Gson object
 Gson gson = new Gson();

 // convert your set to json
 String jsonUsersSet = gson.toJson(users);

 // print your generated json
 System.out.println("jsonUsersSet: " + jsonUsersSet);

Convert from JSON string to your Java object:

 // Converts JSON string into a set of user object
 Type type = new TypeToken<Set<User>>(){}.getType();
 Set<User> userSet = gson.fromJson(jsonUsersSet, type);

 // print your Set<User>
 System.out.println("userSet : " + userSet);

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"}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM