简体   繁体   中英

Converting List to JSON in Java with correct extension

I am trying to create a List of errors with different codes and converting them to JSON using gson .

String jsonString = gson.toJson(Errors.getErrors());

And here is the class:

public class Errors {

    private static List<SingleError> errors = new ArrayList<>();

    public static List<SingleError> getErrors() {
        return errors;
    }

    public static void addError(SingleError singleError) {
        errors.add(singleError);
    }

}

The output I get:

[
    {
        "code": "bad_signal"
    }
]

The output I need:

{
   "errors": [
       {
          "code": "bad_signal"
       }
    ]
}

What am I missing in the Errors class the get the output I need?
It would be better if it would be added in the class without just adding string to json conversion.

EDIT
As schomsel suggested, I should use this line to get the output I need.

gson.toJson(Collections.singletonMap("errors", Errors.getErrors()))

And it did work but I failed to mention that I am also using Servlet to return the String and setting this header, which deletes the "errors".

resp.setHeader("Content-Type", "application/json");

What is the correct header I need to use here?

Obviously, you should understand that desired json representation is for Errors class itself and not contained erros list only so your code is to be tweaked so you can pass Errors class instance as input to - gson.toJson(...)

Two solutions ,

First Solution - make Errors fields and methods non - static and pass on Errors instance instead of errors List to call - gson.toJson(ErrorsInstance);

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;

class Errors {  
 private List<SingleError> errors = new ArrayList<>();
 public List<SingleError> getErrors() {
            return errors;
 }

 public void addError(SingleError singleError) {
            errors.add(singleError);
 }

Second Solution - if fields & methods can't be made static then add a new method to get Errors instance via private constructor and then create Gson object from GsonBuilder so that static fields can be included during serialization.

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class Errors {


   // private constructor 
    private Errors(List<SingleError> errors) {
        Errors.errors = errors;
    }

    private static List<SingleError> errors = new ArrayList<>();

    public static List<SingleError> getErrors() {
        return errors;
    }

   // New method to return Errors instance 
    public static Errors getErrorsInstance() {
        return new Errors(errors);
    }

    public static void addError(SingleError singleError) {
        errors.add(singleError);
    }

    }

//To include static fields during serialization & ignore only transient fields- if not done then json would be empty

GsonBuilder gsonBuilder = new GsonBuilder();
        // Allowing the serialization of static fields
    gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
    // Creates a Gson instance based on the current configuration
        Gson gson = gsonBuilder.create();
        Errors errorsInstance = Errors.getErrorsInstance();
        String jsonStringTest = gson.toJson(errorsInstance );

EDIT:

For Second solution, you wouldn't need a private constructor & new method - getErrorsInstance() . You can simply feed new Errors() to gson.toJson(...) . What you need is only static field inclusion in deserialization & same would hold true for solution # 1 too. So you don't need to modify any code, just make sure with GsonBuilder that static fields are included & pass on Errors instance instead of contained list.

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