如何在Arraylist中存储json数据?

时间:2016-03-30 05:55:20

标签: java json arraylist elasticsearch

我有以下代码,我将Elasticsearch中的json数据存储在本地驱动器中存储的文件中。相反,我想将数据存储在Arraylist中,因此我可以将其传递给UI以显示在前端。

try {           
    HttpGet request = new HttpGet("http://localhost:9200/indexname/_search?pretty=1&size=100&q=name:%22Test%22");             
    HttpResponse resp = client.execute(request);
    HttpEntity entity = resp.getEntity();

    byte[] buffer = new byte[1024];
    if (entity != null) {
        InputStream input = entity.getContent();
        FileWriter file = new FileWriter("/localpath/data.json");

        try {
            int bytesRead = 0;
            BufferedInputStream in = new BufferedInputStream(input);

            while ((bytesRead = in.read(buffer)) != -1) {
                String chunk = new String(buffer, 0, bytesRead);
                System.out.println(chunk);
                file.write(chunk);                  
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { file.close(); inputStream.close(); } catch (Exception ignore) {}
        }               
    }
}

JSON数据的格式为:

{
    "took": 9,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 6.3519955,
        "hits": [
            {
                "_index": "indexname",
                "_type": "status",
                "_id": "eb825358-93d7-4a2f-9227-9b060cbc323a",
                "_score": 6.3519955,
                "_source": {
                    "name": "Test",
                    "ID": "ABCD",
                    "Number": "23222",
                    "SecCode": "124"
                }
            },
            {
                "_index": "indexname",
                "_type": "status",
                "_id": "eb825358-93d7-4a2f-9227-9b060cbc323b",
                "_score": 6.3519955,
                "_source": {
                    "name": "Test",
                    "ID": "CDEF",
                    "Number": "5678",
                    "SecCode": "120"
                }
            }
        ]
    }
}

在我的arraylist中,我只想存储ID和数字。

任何帮助将不胜感激?感谢

1 个答案:

答案 0 :(得分:0)

public static List<Pattern> pattern(){
    ArrayList<Pattern> patterns = new ArrayList<>();
    Gson gson = new Gson();
    JsonParser jsonParser = new JsonParser();
    try {
        BufferedReader bufferedReader  = new BufferedReader(new FileReader("MyJsons/objects.json"));
        JsonElement jsonElement = jsonParser.parse(bufferedReader);

        //Create generic type
        Type type = new TypeToken<List<Pattern>>() {}.getType();
        return gson.fromJson(jsonElement, type);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return patterns;        
}