Reputation: 31
This is the sample of a JSON object. I want to extract the part of it and display those values in a jTable (SWING) in JAVA. 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.
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.
Upvotes: 1
Views: 8797
Reputation: 163
Take a look at this simple tutorials: 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:
[{eName=John, eAge=25, eAddress=UK}, {eName=Alex, eAge=24, eAddress=Australia}]
Upvotes: 2
Reputation: 334
Instead of using split()
, use:
int index= splits[1].indexOf("\\}]");
String result = splits[1].substring(0,index);
Upvotes: 0