Reputation: 93
how to extract a json node from another json .for example I want to fetch the "Company Name" i.e "kjh".But using this json parser code I am able to fetch the whole json and not only comapnt name..Can somebody help
jsonObject = (JSONObject) new org.json.simple.parser.JSONParser().parse(domainRequest);
final String companyName = (String) jsonObject.get("companyName");
here is the Json content:
{"companyName":{"Company Name:":"kjh","Address 1:":"kjhhkh","Address 2:":"hkjhkj","Address 3:":"hkjhhkj","Address 4:":"kjhj","Postcode:":898,"Default Email Address:":"kkjkh@y","Company Registration No:":98,"VAT No:":89098,"Website":"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000"}}
{"companyName" : {
"Company Name:":"kjh",
"Address 1:":"kjhhkh",
"Address 2:":"hkjhkj",
"Address 3:":"hkjhhkj",
"Address 4:":"kjhj",
"Postcode:":898,
"Default Email Address:":"kkjkh@y","Company Registration No:":98,
"VAT No:":89098,
"Website":"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000"
}}
Upvotes: 0
Views: 1083
Reputation: 151
It is weird your json format. You should be check it out.
Remove colon from children property name.
String json =
"{\"companyName\" : {\n" +
" \"Company Name:\":\"kjh\",\n" +
" \"Address 1:\":\"kjhhkh\",\n" +
" \"Address 2:\":\"hkjhkj\",\n" +
" \"Address 3:\":\"hkjhhkj\",\n" +
" \"Address 4:\":\"kjhj\",\n" +
" \"Postcode:\":898,\n" +
" \"Default Email Address:\":\"kkjkh@y\",\"Company Registration No:\":98,\n" +
" \"VAT No:\":89098,\n" +
" \"Website\":\"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000\"\n" +
" }}";
JsonElement jsonElement = new Gson().fromJson(json, JsonElement.class);
String companyName = jsonElement.getAsJsonObject().get("companyName").getAsJsonObject().get("Company Name:").getAsString();
System.out.println(companyName);
Upvotes: 0
Reputation: 26077
You missed 1 step, you are actually getting a map (key-value pair), using this map get company name
public static void main(String[] args) throws JSONException {
String domainRequest = "{\"companyName\":{\"Company Name:\":\"kjh\",\"Address 1:\":\"kjhhkh\",\"Address 2:\":\"hkjhkj\",\"Address 3:\":\"hkjhhkj\",\"Address 4:\":\"kjhj\",\"Postcode:\":898,\"Default Email Address:\":\"kkjkh@y\",\"Company Registration No:\":98,\"VAT No:\":89098,\"Website\":\"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000\"}}";
JSONObject jsonObject = new JSONObject(domainRequest);
JSONObject jsonMap = (JSONObject) jsonObject.get("companyName"); // Generates HashMap, key-value pair
String companyName = (String) jsonMap.get("Company Name:"); // from map prepared above get key value
System.out.println(companyName);
}
Output
kjh
Upvotes: 2