在JAVA中提取JSON对象的一部分

时间:2014-11-17 20:31:40

标签: java json

这是JSON对象的示例。我想提取它的一部分并在JAVA中的jTable(SWING)中显示这些值。键作为表列名称和值分别作为行数据。

[
   {
      "_id":{
         "date":"xxxxxxxx",
         "time":"xxxxxxx",
         "inc":"xxxx"
      },
      "DOCUMENTS":[
         {
            "EName":"John",
            "eAge":"25",
            "eAddress":"UK"
         },

         {
            "EName":"Alex",
            "eAge":"24",
            "eAddress":"Australia"
         }
      ]
   }
]

我想提取这部分内容。

      [
         {
            "EName":"John",
            "eAge":"25",
            "eAddress":"UK"
         },
         {
            "EName":"Alex",
            "eAge":"24",
            "eAddress":"Australia"
         }
      ]

我用这种方式得到答案。这里jsonstring是包含上述数据的字符串。

        String[] splits = jsonString.split("DOCUMENTS\":");
        String[] splits2 = splits[1].split("\\}]", 2);
        System.out.println("spilted  :"+splits2[0]);

但它正在给我答案

[{"EName":"John","eAge":"25","eAddress":"UK"}, 
 {"EName":"Alex","eAge":"24","eAddress":"Australia"

它取下了封闭的方括号。

我怎样才能得到正确的答案?非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

看看这个简单的教程: http://wiki.fasterxml.com/JacksonInFiveMinutes http://www.tutorialspoint.com/json/json_java_example.htm

示例:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class KroplaTest {
    private static final String JSON = "{\"id\":{ "
            + "\"date\":\"xxxxxxxx\","
            + "\"time\":\"xxxxxxx\","
            + "\"inc\":\"xxxx\""
            + "},"
            + "\"documents\":["
            + "{"
            + " \"eName\":\"John\","
            + " \"eAge\":\"25\","
            + " \"eAddress\":\"UK\""
            + "},"
            + "{"
            + " \"eName\":\"Alex\","
            + " \"eAge\":\"24\","
            + " \"eAddress\":\"Australia\""
            + "} ]} ";

    public static void main(String[] args) {
        final ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String,Object> map = new HashMap<String,Object>();
            map = mapper.readValue(JSON, new TypeReference<HashMap<String,Object>>(){});
            System.out.println(map.get("documents").toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这将打印到sysout:

[{eName=John, eAge=25, eAddress=UK}, {eName=Alex, eAge=24, eAddress=Australia}]

答案 1 :(得分:1)

不使用split(),而是使用:

int index= splits[1].indexOf("\\}]");
String result = splits[1].substring(0,index);