How to convert ArrayList of custom class to JsonArray in Java?

前端 未结 7 2096
一个人的身影
一个人的身影 2021-02-03 22:18

I am trying to convert ArrayList of custom class to JsonArray. Below is my code. It executes fine but some JsonArray elements come as zeros even though they are numbers in the A

相关标签:
7条回答
  • 2021-02-03 22:32

    As an additional answer, it can also be made shorter.

    List<Customer> customerList = CustomerDB.selectAll();
    
    JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,
                new TypeToken<List<Customer>>() {
                }.getType());
    
    0 讨论(0)
  • 2021-02-03 22:40

    Use google gson jar, Please see sample code below,

        public class Metric {
            private int id;
            ...
           setter for id
            ....
           getter for id
        }
    
        Metric metric = new Metric();
        metric.setId(1);
    
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls();
        Gson gson = gsonBuilder.create();
        System.out.println(gson.toJson(metric));
    
    StringBuffer jsonBuffer = new StringBuffer("{ \"rows\": [");
    List<Metric> metrices = new ArrayList<Metric>();
    // assume you have more elements in above arraylist
    boolean first = true;
    for (Metric metric : metrices) {
           if (first)
          first = false;
        else
          jsonBuffer.append(",");
          jsonBuffer.append(getJsonFromMetric(metric));
    }
    jsonBuffer.append("]}");
    
    private String getJsonFromMetric(Metric metric) {
    GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls();
        Gson gson = gsonBuilder.create();
        return gson.toJson(metric);
    }
    
    0 讨论(0)
  • 2021-02-03 22:43

    Below code should work for your case.

    List<Customer> customerList = CustomerDB.selectAll();
    
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
    
    if (! element.isJsonArray() ) {
    // fail appropriately
        throw new SomeException();
    }
    
    JsonArray jsonArray = element.getAsJsonArray();
    

    Heck, use List interface to collect values before converting it JSON Tree.

    0 讨论(0)
  • 2021-02-03 22:43

    Don't know how well this solution performs compared to the other answers but this is another way of doing it, which is quite clean and should be enough for most cases.

    ArrayList<Customer> customerList = CustomerDB.selectAll();
    Gson gson = new Gson();
    String data = gson.toJson(customerList);
    JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();
    

    Would love to hear from someone else though if, and then how, inefficient this actually is.

    0 讨论(0)
  • 2021-02-03 22:45

    For Anyone who is doing it in Kotlin, you can get it this way,

    val gsonHandler = Gson()
    val element: JsonElement = gsonHandler.toJsonTree(yourListOfObjects, object : TypeToken<List<YourModelClass>>() {}.type)
    
    0 讨论(0)
  • 2021-02-03 22:47

    List<> is a normal java object, and can be successfully transformed using standard gson object api. List in gson looks like this:

    "libraries": [
        {
          //Containing object 
        },
        {
          //Containing object 
        }
       ],
    ...
    
    0 讨论(0)
提交回复
热议问题