如何将List <class>转换为Array?

时间:2017-06-18 17:55:53

标签: java arrays string class

public class myClass {
    private String myVar1;
    private String myVar2;
}

List<myClass> list = generateListWithGson();

System.out.println(list.toString());
// returns
[
  myClass(myVar1=OneDummyString, myVar2=TwoDummyString),
  myClass(myVar1=OneDummyString, myVar2=TwoDummyString),
  ...
]

我希望将其格式化为:

// desired output:
[
  {
    "myVar1" : "OneDummyString",
    "myVar2" : "TwoDummyString",
  },
  {
    "myVar1" : "OneDummyString",
    "myVar2" : "TwoDummyString",
  },
  ...
]

3 个答案:

答案 0 :(得分:2)

npm run port4900

应该工作

答案 1 :(得分:-1)

Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

答案 2 :(得分:-2)

重写myClass的toString()方法。 然后将List转换为myClass对象数组(请参阅Dev的答案)。