繁体   English   中英

使用hashmap的arraylist创建hashmap

[英]Create hashmap with arraylist of hashmap

我有以下结构

{
    "abc":[
        {
            "bc":"52",
            "gd":"jjksa"
        }
    ]
}

现在,我需要从客户端创建相同的结构,并像上述格式一样发送数据。 我假设结构是这样的。

HashMap<String, ArrayList<HashMap<String, String>>> hashmap = new HashMap<String, ArrayList<new HashMap<String, String>()>>();

HashMap<String, String> obj1 = new HashMap<String, String>();

ArrayList<String> arraylist = new ArrayList<String>();

obj1.put("bc", "52");
obj1.put("gd", "jjksa");

arraylist.add(obj1);

hashmap.put("metrics", arraylist)

如上例所示,任何可以帮助我创建正确地图的人。

使用JSON处理器,例如Jackson

import org.codehaus.jackson.map.ObjectMapper;

// ...

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(hashmap);

下面的代码为我工作。 但是,你们提出的建议无疑是有价值的。 我将进行相应的更改以使结构更好。

HashMap<String, Object> hashmap = new HashMap<String, Object>();

HashMap<String, String> obj1 = new HashMap<String, String>();

ArrayList arraylist = new ArrayList();

obj1.put("bc", "52");
obj1.put("gd", "jjksa");

arraylist.add(obj1);

hashmap.put("metrics", arraylist);

Gson json = new Gson();

System.out.print(json.toJson(hashmap));

HashMap的toString方法很简单,就像json一样输出值,但没有双引号(“)。:)

sp00m的答案非常有效。 除此之外,您还可以使用Google的Gson

import java.util.ArrayList;
import java.util.HashMap;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;


public class GsonParser {

    public static void main(String[] args) throws Exception {
        HashMap<String, ArrayList<HashMap<String, String>>> hashmap = new HashMap<String, ArrayList<HashMap<String, String>>>();

        HashMap<String, String> obj1 = new HashMap<String, String>();

        ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();

        obj1.put("bc", "52");
        obj1.put("gd", "jjksa");

        arraylist.add(obj1);

        //Hashmap toString
        hashmap.put("metrics", arraylist);
        System.out.println(hashmap); //Prints : {metrics=[{bc=52, gd=jjksa}]}

        //Jackson Example
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(hashmap);
        System.out.println(json); //Prints : {"metrics":[{"bc":"52","gd":"jjksa"}]}

        //Gson Example
        Gson gson = new Gson();
        String json2 = gson.toJson(hashmap);
        System.out.println(json2); //Prints : {"metrics":[{"bc":"52","gd":"jjksa"}]}
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM