如何将linkedhashmap转换为jsonobject

piah890a  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(3604)

arraylist条目,而这个条目是linkedhashmap类型的,我想把它转换成JSONObject来使用,我该怎么做呢?

  1. for(Object entry : entries){
  2. JSONObject entryToProcess = (JSONObject) entry;
  3. }
efzxgjgh

efzxgjgh1#

嗨,这个转换工具应该可以。这里发生的是调用方法 .getKeys() 在linkedhashmap对象上获取所有密钥。然后针对每个键,从linkedhashmap检索信息并将其放入jsonobject中

  1. // Your input LinkedHashMap
  2. LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
  3. // Providing general values for the test
  4. linkedHashMap.put("First key", "First value");
  5. linkedHashMap.put("Second key", "Second value");
  6. linkedHashMap.put("Third key", "Third value");
  7. // Initialization of the JSONObject
  8. JSONObject jsonObject = new JSONObject();
  9. // for-each key in the LinkedHashMap get the value and put both of
  10. // them into the JSON
  11. for (String key : linkedHashMap.keySet()) {
  12. jsonObject.put(key, linkedHashMap.get(key));
  13. }

你关心的部分应该是for循环。
干杯,

展开查看全部
m1m5dgzv

m1m5dgzv2#

简单的jsonobject构造函数就可以做到这一点

  1. for(Object entry : entries){
  2. JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
  3. }

样品:

  1. LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
  2. linkedHashMap.put("A",1);
  3. linkedHashMap.put("some key","some value");
  4. Map<String, String> someMap = new HashMap<>();
  5. someMap.put("map-key-1","map-value-1");
  6. someMap.put("map-key-2","map-value-2");
  7. linkedHashMap.put("another key",someMap);
  8. JSONObject jsonObject = new JSONObject(linkedHashMap);
  9. System.out.println(jsonObject.toJSONString());

输出:

  1. {
  2. "another key": {
  3. "map-key-1": "map-value-1",
  4. "map-key-2": "map-value-2"
  5. },
  6. "A": 1,
  7. "some key": "some value"
  8. }
展开查看全部

相关问题