[英]Extract a part of the JSON object in JAVA
This is the sample of a JSON object. 这是JSON对象的示例。 I want to extract the part of it and display those values in a jTable (SWING) in JAVA. 我想提取它的一部分并在JAVA中的jTable(SWING)中显示这些值。 Keys as table column names and values as row data respectively. 键作为表列名称和值分别作为行数据。
[
{
"_id":{
"date":"xxxxxxxx",
"time":"xxxxxxx",
"inc":"xxxx"
},
"DOCUMENTS":[
{
"EName":"John",
"eAge":"25",
"eAddress":"UK"
},
{
"EName":"Alex",
"eAge":"24",
"eAddress":"Australia"
}
]
}
]
I want to extract this part. 我想提取这部分内容。
[
{
"EName":"John",
"eAge":"25",
"eAddress":"UK"
},
{
"EName":"Alex",
"eAge":"24",
"eAddress":"Australia"
}
]
I used this way to get the answer. 我用这种方式得到答案。 Here jsonstring is the string that contains above data. 这里jsonstring是包含上述数据的字符串。
String[] splits = jsonString.split("DOCUMENTS\":");
String[] splits2 = splits[1].split("\\}]", 2);
System.out.println("spilted :"+splits2[0]);
but it is giving me the answer as 但它给了我答案
[{"EName":"John","eAge":"25","eAddress":"UK"},
{"EName":"Alex","eAge":"24","eAddress":"Australia"
it removed the closed square bracket. 它取下了封闭的方括号。
How can I get the correct answer? 我怎样才能得到正确的答案? Your help is much appreciated. 非常感谢您的帮助。
Take a look at this simple tutorials: http://wiki.fasterxml.com/JacksonInFiveMinutes http://www.tutorialspoint.com/json/json_java_example.htm 看看这个简单的教程: http : //wiki.fasterxml.com/JacksonInFiveMinutes http://www.tutorialspoint.com/json/json_java_example.htm
example: 例:
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();
}
}
}
This will print to sysout: 这将打印到sysout:
[{eName=John, eAge=25, eAddress=UK}, {eName=Alex, eAge=24, eAddress=Australia}]
Instead of using split()
, use: 而不是使用split()
,使用:
int index= splits[1].indexOf("\\}]");
String result = splits[1].substring(0,index);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.