arraylist条目,而这个条目是linkedhashmap类型的,我想把它转换成JSONObject来使用,我该怎么做呢?
for(Object entry : entries){ JSONObject entryToProcess = (JSONObject) entry;}
for(Object entry : entries){
JSONObject entryToProcess = (JSONObject) entry;
}
efzxgjgh1#
嗨,这个转换工具应该可以。这里发生的是调用方法 .getKeys() 在linkedhashmap对象上获取所有密钥。然后针对每个键,从linkedhashmap检索信息并将其放入jsonobject中
.getKeys()
// Your input LinkedHashMap LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); // Providing general values for the test linkedHashMap.put("First key", "First value"); linkedHashMap.put("Second key", "Second value"); linkedHashMap.put("Third key", "Third value"); // Initialization of the JSONObject JSONObject jsonObject = new JSONObject(); // for-each key in the LinkedHashMap get the value and put both of // them into the JSON for (String key : linkedHashMap.keySet()) { jsonObject.put(key, linkedHashMap.get(key)); }
// Your input LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
// Providing general values for the test
linkedHashMap.put("First key", "First value");
linkedHashMap.put("Second key", "Second value");
linkedHashMap.put("Third key", "Third value");
// Initialization of the JSONObject
JSONObject jsonObject = new JSONObject();
// for-each key in the LinkedHashMap get the value and put both of
// them into the JSON
for (String key : linkedHashMap.keySet()) {
jsonObject.put(key, linkedHashMap.get(key));
你关心的部分应该是for循环。干杯,
m1m5dgzv2#
简单的jsonobject构造函数就可以做到这一点
for(Object entry : entries){ JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);}
JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
样品:
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();linkedHashMap.put("A",1);linkedHashMap.put("some key","some value");Map<String, String> someMap = new HashMap<>();someMap.put("map-key-1","map-value-1");someMap.put("map-key-2","map-value-2");linkedHashMap.put("another key",someMap);JSONObject jsonObject = new JSONObject(linkedHashMap);System.out.println(jsonObject.toJSONString());
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A",1);
linkedHashMap.put("some key","some value");
Map<String, String> someMap = new HashMap<>();
someMap.put("map-key-1","map-value-1");
someMap.put("map-key-2","map-value-2");
linkedHashMap.put("another key",someMap);
JSONObject jsonObject = new JSONObject(linkedHashMap);
System.out.println(jsonObject.toJSONString());
输出:
{ "another key": { "map-key-1": "map-value-1", "map-key-2": "map-value-2" }, "A": 1, "some key": "some value"}
{
"another key": {
"map-key-1": "map-value-1",
"map-key-2": "map-value-2"
},
"A": 1,
"some key": "some value"
2条答案
按热度按时间efzxgjgh1#
嗨,这个转换工具应该可以。这里发生的是调用方法
.getKeys()
在linkedhashmap对象上获取所有密钥。然后针对每个键,从linkedhashmap检索信息并将其放入jsonobject中你关心的部分应该是for循环。
干杯,
m1m5dgzv2#
简单的jsonobject构造函数就可以做到这一点
样品:
输出: