简体   繁体   中英

How do I convert a java class that has an arraylist to json

I use the Gson library and I have a class that has an arraylist as one of its members.
I add different object types to this arraylist then I serialize it to json

public class MethodParameter {
    private String className;
    private String methodName;
    private ArrayList parameters;

    public MethodParameter(){
        parameters = new ArrayList();
    }

    public String getClassName(){
        return className;
    }

    public String getMethodName(){
        return methodName;
    }

    public List<Object> getParameters(){
        return parameters;
    }

    public void setClassName(String value){
        className = value;
    }

    public void setMethodName(String value){
        methodName = value;
    }

    public void setParameters(ArrayList value){
        parameters = value;
    }
}

Then I convert as follows:

Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<MethodParameter>() {}.getType();
String json = gson.toJson(mp, type);  

but all I get is :

{"className":"MainClass","methodName":"Test","parameters":[]}

Parameters is an arraylist to which I add classes of different types. How do I get it to create the correct json result?

I tried your code and 2 things,

  1. define the MethodParameter.parameters as a list (just a best practice)
  2. the issue may be in the way you are manipulating the list in the MethodParameter object...

anyway here is a snippet working as you want it to do:

Example:

public static void main(String[] args) {
    MethodParameter mp = new MethodParameter();
    mp.setClassName(String.class.getCanonicalName());
    mp.setMethodName("replace");
    List<String> parametersList = new ArrayList<String>();
    parametersList.add("target");
    parametersList.add("sequence");
    mp.setParameters(parametersList);
    //
    Gson gson = new Gson();
    java.lang.reflect.Type type = new TypeToken<MethodParameter>() {
            }.getType();
    String json = gson.toJson(mp, type);
    System.out.println(json);
    }

but in my opinion you can generate the json by just doing this:

System.out.println(gson.toJson(mp, MethodParameter.class));

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