使用json simple在Java中将列表转换为JsonObject

使用json simple在Java中将列表转换为JsonObject,java,json,list,json-simple,Java,Json,List,Json Simple,我有一张单子- List<Item> items = new ArrayList<Item>; List items=newarraylist; 其中包括项目-[名字、abc、姓氏、pqr、id、1] 我需要使用json简单库在java中将此列表转换为以下格式的JSONObject- {“名字”:“abc”,“姓氏”:“pqr”,“id”:“1”} 我怎样才能做到这一点? 我只是一个初学者。任何帮助都将不胜感激。提前谢谢。得到答案- 首先将列表转换为Map,然后转换为

我有一张单子-

List<Item> items = new ArrayList<Item>;
List items=newarraylist;
其中包括项目-[名字、abc、姓氏、pqr、id、1]

我需要使用json简单库在java中将此列表转换为以下格式的JSONObject-

{“名字”:“abc”,“姓氏”:“pqr”,“id”:“1”}

我怎样才能做到这一点? 我只是一个初学者。任何帮助都将不胜感激。提前谢谢。

得到答案-

首先将列表转换为Map,然后转换为Json-

public Map<String, String> test() {

    Map<String, String> result = items.stream().collect(Collectors.toMap(Item::getValue, Item::getType)); //Converts List items to Map

    System.out.println("Result  : " + result);

    JSONObject json = new JSONObject(result); //Converts MAP to JsonObject

    System.out.println("JSON : " + json); //prints {"firstname":"abc","lastname":"pqr","id":"1"}
    return result;
}
publicmap测试(){
映射结果=items.stream().collect(Collectors.toMap(Item::getValue,Item::getType));//将列表项转换为映射
System.out.println(“结果:+Result”);
JSONObject json=新建JSONObject(结果);//将映射转换为JSONObject
System.out.println(“JSON:+JSON);//打印{“firstname”:“abc”,“lastname”:“pqr”,“id”:“1”}
返回结果;
}
得到答案了吗-

首先将列表转换为Map,然后转换为Json-

public Map<String, String> test() {

    Map<String, String> result = items.stream().collect(Collectors.toMap(Item::getValue, Item::getType)); //Converts List items to Map

    System.out.println("Result  : " + result);

    JSONObject json = new JSONObject(result); //Converts MAP to JsonObject

    System.out.println("JSON : " + json); //prints {"firstname":"abc","lastname":"pqr","id":"1"}
    return result;
}
publicmap测试(){
映射结果=items.stream().collect(Collectors.toMap(Item::getValue,Item::getType));//将列表项转换为映射
System.out.println(“结果:+Result”);
JSONObject json=新建JSONObject(结果);//将映射转换为JSONObject
System.out.println(“JSON:+JSON);//打印{“firstname”:“abc”,“lastname”:“pqr”,“id”:“1”}
返回结果;
}

是您提到的列表数据常量,第一个元素是name,第二个元素是它的值,比如wise on和on???另外,您可以添加Item类的代码吗?is
Item
a
String
?或者其他类型的类?不,不是常数。。通过在文本字段中输入值,我从BeanItem中获取列表中的值。您能把您的Item类结构放在下面吗?因为您需要将list转换为map,然后再转换为json。所以需要显示您的Item类与您提到的list数据常量完全相似,第一个元素是name,第二个元素是它的值,如wise on和on???另外,您可以添加Item类的代码吗?isItemaString?或者其他类型的类?不,不是常数。。通过在文本字段中输入值,我从BeanItem中获取列表中的值。您能把您的Item类结构放在下面吗?因为您需要将list转换为map,然后再转换为json,所以需要显示Item类的确切外观