How do I extract exact value from Json - java

Below Json I want to get only first mail value (abc#test.com) using java. Please anybody can suggest how do I extract exact value from below Json. Thanks in advance.
{
"profiles": [
{
"userId": "1234",
"content": {
"address": {
"business": {
"country": "IN",
"locality": "Chennai",
}
},
"name": {
"first": "abc",
"last": "abc"
},
"mail": [
"abc#test.com",
"xyz#test.com"
]
}
}
]
}

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
String jsonstring = "{\"profiles\":[{\"userId\":\"1234\",\"content\":{\"address\":{\"business\":{\"country\":\"IN\",\"locality\":\"Chennai\"}},\"name\":{\"first\":\"abc\",\"last\":\"abc\"},\"mail\":[\"abc#test.com\",\"xyz#test.com\"]}}]}";
System.out.println(jsonstring);
JSONObject jsonObject = new JSONObject(jsonstring);
JSONArray profiles = jsonObject.getJSONArray("profiles");
for (int i = 0; i < profiles.length(); i++) {
JSONObject curProfile= (JSONObject) profiles.get(i);
JSONArray mails= (JSONArray)((JSONObject)curProfile.get("content")).get("mail");
System.out.println(mails.get(0));
}
}
}
as they have already said json standard doesn't impose ordering, so be careful

I can able to get mail by using below code
//root = my json
JsonObject rootobj = root.getAsJsonObject();
JsonArray profilesItems = rootobj.getAsJsonArray("profiles");
JsonObject firstValue = profilesItems.get(0).getAsJsonObject().getAsJsonObject("content");
JsonElement emails = firstValue.get("mail");
String mail = emails.getAsJsonArray().get(0).getAsString();

Related

How can i remove a root node from a json after converting from xml, using java

I have the following code with me:
import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);
}
}
It gives the output as shown below:
{
"users": {
"report": {
"sub": "eng",
"score": 30
},
"user": {
"name": "test1",
"age": 20
}
}
}
But i want to remove this root node, and the expected output is:
{
"report": {
"sub": "eng",
"score": 30
},
"user": {
"name": "test1",
"age": 20
}
}
Can anyone help me?.. Thanks in advance!
Instead of removing just assign the root node value to jsonObject
jsonObject = (JSONObject) jsonObject.get(jsonObject.keys().next());
System.out.println(jsonObject);
You can also specify the name of the root node directly
jsonObject = (JSONObject) jsonObject.get("users");
Output:
{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}

How to parse JSON String to String in Java

I have a JSON string, how can I parse it and just get the valueString in java?
{
"resourceType": "Bundle",
"id": "0",
"entry": [
{
"resource": {
"resourceType": "Basic",
"extension": [
{
"url": "http://ith.sahra.com/extensions#uploadid",
"valueString": "1589355494289_655"
}
]
}
}
]
}
This is my code, I tried to call extension I got null but I got response while calling entry
public static String ParsingValue(String valuepass) throws org.json.simple.parser.ParseException{
Object obj = new JSONParser().parse(valuepass);
JSONObject jo = (JSONObject) obj;
//JSONArray msg = (JSONArray) jo.getClass();
JSONArray result = (JSONArray) jo.get("entry");
}
The easiest way to parse a string through Jackson parser
Eg:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"anshul\",\"age\":29}";
Map<String, Object> map = mapper.readValue(json, Map.class);
Try this, it should solve your problem.

How to parse JSON String to java object with jackson?

I am currently having trouble trying to parse this VCAP_SERVICES to java objects. I do not quite understand how to structure the POJO to allow it to map the values from the json string. Can someone please help me structure my pojo so that it is aligns with the json string?
I want to create objects for both of the credentials: accessToken... jdbcurl.
VCAP_SERVICES
"VCAP_SERVICES": {
"user-provided": [
{
"credentials": {
"accessTokenUri": "tokenurl",
"apiUrl": "apiurl",
"clientId": "typeofID",
"clientSecret": "secretAf",
"scope": "none"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "OAuth2",
"tags": []
},
{
"credentials": {
"jdbcUrl": "jdbc:oracle:connection[host]:[port]/service",
"spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver",
"spring.datasource.initialize": "false"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "Database",
"tags": []
}
]
Java Class
ObjectMapper mapper = new ObjectMapper();
//json String to Object
CupsProperties properties = mapper.readValue(VCAP_Services, CupsProperties.class);
System.out.println(properties.getJdbcUrl() + "!!!!!!!!!!!!!!!!!!!");
POJOS
public class UserProviderWrapper {
#JsonProperty("user-provided")
public List<CupsProperties> cupsProperties;
#JsonProperty("syslog_drain_url")
public String syslog_drain_url;
#JsonProperty("volume_mounts")
public List<String> volume_mounts;
#JsonProperty("label")
public String label;
#JsonProperty("name")
public String name;
#JsonProperty("tags")
public List<String> tags;
//getters and setters
public class CupsProperties {
#JsonProperty("jdbcUrl")
public String jdbcUrl;
#JsonProperty("spring.datasource.driver-class-name")
public String driver;
#JsonProperty("spring.datasource.initialize")
public String initialize;
//getters and setters
Error
Unrecognized field "user-provided" (class rest.springframework.model.CupsProperties), not marked as ignorable (2 known properties: "jdbcUrl", "dataSource"])
at [Source: {"user-provided":[{ "credentials": { "jdbcUrl": "jdbc:oracle:thin:user/pass//host:port/service", "spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver", "spring.datasource.initialize": "false" }, "syslog_drain_url": "", "volume_mounts": [ ], "label": "user-provided", "name": "Oracle", "tags": [ ] }]}; line: 1, column: 19] (through reference chain: rest.springframework.model.CupsProperties["user-provided"])
Check below solution and see if it fulfills your need. You can build on to it if you need to parse more fields.
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser {
public static void main(String[] args) {
String VCAP_Services = "{\"userProvided\": [{\"credentials\": {\"accessTokenUri\": \"tokenurl\",\"apiUrl\": \"apiurl\",\"clientId\": \"typeofID\",\"clientSecret\": \"secretAf\",\"scope\": \"none\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"OAuth2\",\"tags\": []},{\"credentials\": {\"jdbcUrl\": \"jdbc:oracle:connection[host]:[port]/service\",\"spring.datasource.driver-class-name\": \"oracle.jdbc.OracleDriver\",\"spring.datasource.initialize\": \"false\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"Database\",\"tags\": [] } ] } ";
CupsProperties properties=null;
try {
JSONParser jsonParser = new JSONParser();
JSONObject vcapServiceJSONObject = (JSONObject) jsonParser.parse(VCAP_Services);
for(Object key: vcapServiceJSONObject.keySet()){
String keyStr = (String) key;
JSONArray userProvidedList = (JSONArray) vcapServiceJSONObject.get(keyStr);
Iterator i = userProvidedList.iterator();
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
JSONObject credentialsObject = (JSONObject) innerObj.get("credentials");
if(credentialsObject.containsKey("jdbcUrl")){
//set to your pojo objects
System.out.println("JDBC url:" + credentialsObject.get("jdbcUrl"));
}
if(credentialsObject.containsKey("accessTokenUri")){
//set to your pojo objects
System.out.println("Access token URI:" + credentialsObject.get("accessTokenUri"));
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output
Access token URI:tokenurl
JDBC url:jdbc:oracle:connection[host]:[port]/service

Parse JSON object recursively - Java

I have a JSON with list of Objects and any of the item in the list can have null or the same object as a value for a key. I am looking for a faster way to parse the json to arrive at my final result.
The data structure looks like -
[
{
"firstName": "Bruce",
"familyMembers": null
},
{
"firstName": "Gates Family",
"familyMembers": [
{
"firstName": "Bill",
"familyMembers": null
},
{
"firstName": "Steve",
"familyMembers": null
}
]
},
{
"firstName": "Lee",
"familyMembers": null
},
{
"firstName": "Chan",
"familyMembers": null
}
]
The output should be a set = ("Bruce", "Bill", "Steve", "Lee", "Chan").
I am looking for a best possible way to do this in Java, such that i dont increase my response time by getting caught in this parsing hell.
Appreciate your time on this.
Try my recursive implementation.
public static void jsonArrayToSet(JSONArray jAry, Set<String> result, String targetKey, String subArrayKey, boolean includeNode){
try {
for (int i = 0; i < jAry.length(); i++) {
JSONObject jObj = jAry.getJSONObject(i);
boolean hasSubArray = false;
JSONArray subArray = null;
if(jObj.has(subArrayKey)){
Object possibleSubArray = jObj.get(subArrayKey);
if(possibleSubArray instanceof JSONArray){
hasSubArray = true;
subArray = (JSONArray) possibleSubArray;
}
}
if(hasSubArray){
if(includeNode){
result.add(jObj.getString(targetKey));
}
jsonArrayToSet(subArray, result, targetKey, subArrayKey, includeNode);
} else {
result.add(jObj.getString(targetKey));
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
jAry: The source JSONArray.
result: The Set you want to write in.
targetKey: The key that maps to an entry which you want to add to result.
subArrayKey: The key that map to a sub-JSONArray.
includeNode: When current JSONOnject is a node containing sub-array, add it to result or not.
In your case, you can call:
jsonArrayToSet(yourJsonArray, yourSet, "firstName", "familyMembers", false);
As mentioned in my comment.
Your first issue would be the content in your JSON file. Based on the standard, it should be wrapped around with a set of { }.
Example
{
"members": [
{
"firstName": "Bruce",
"familyMembers": null
},
{
"firstName": "Gates Family",
"familyMembers": [
{
"firstName": "Bill",
"familyMembers": null
},
{
"firstName": "Steve",
"familyMembers": null
}
]
},
{
"firstName": "Lee",
"familyMembers": null
},
{
"firstName": "Chan",
"familyMembers": null
}
]
}
Also, I think the value "Gates Family" should be part of the output? Since it is under the "FirstName" attribute.
Anyway, here is my solution that is based on the org.json library. It also uses Goggle's GSon library where I use it for reading the JSON file.
import org.json.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
public class solution {
public static final String JSON_DATA_FILE_PATH = "./data/source_37848106.json";
private static boolean hasMoreFamilyName(JSONObject json) {
return json.has("familyMembers") && json.get("familyMembers") != JSONObject.NULL;
}
private static void trackFirstName(Map<String, Integer> nameTracker, JSONObject json) {
if (!nameTracker.containsKey(json.getString("firstName"))) {
nameTracker.put(json.getString("firstName"), /*DUMMY VALUE =*/1);
}
}
private static void getNames(Map<String,Integer> nameTracker, JSONArray jsonArr) {
for (int i = 0; i< jsonArr.length(); i++) {
JSONObject item = jsonArr.getJSONObject(i);
if (hasMoreFamilyName(item)) {
getNames(nameTracker, item.getJSONArray("familyMembers"));
}
trackFirstName(nameTracker, item);
}
}
public static void main(String[] args) {
Map<String, Integer> nameTracker = new HashMap<>();
try {
String text = Files.toString(new File(JSON_DATA_FILE_PATH), Charsets.UTF_8);
JSONObject json = new JSONObject(text);
getNames(nameTracker, json.getJSONArray("members"));
}
catch (Exception ex) {
System.out.println("Something is wrong.");
}
for (Map.Entry<String,Integer> entry : nameTracker.entrySet()) {
System.out.println(entry.getKey());
}
}
You can use ObjectMapper defined in jackson-databind-2.6.5.jar
Define a java class with fields similar to json pattern and then just bind them like:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Family family=objectMapper.readValue(jsonString, Family.class);
Now you will have a java object similar to your json string pattern and you can print it the way you like.

Add a Key value to Json String generated from GSON.toJSON

String jsonResponse=Utils.getGsonInstance().toJson(Object);
jsonResponse returns :
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
End result I am looking for is to wrap this JSON-String in another Key E.g.
{
"MainObj":
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
}
Is there a way I can achieve this using GSON Api ?
I tried ::
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
Output I am getting is :
{"MainObj": "[{\"Key\":\"1",\"Code\":\"11\"}, {\"Key\":\"2",\"Code\":\"22\"}]"}
Continue with GSON like :
public class MainObj {
#SerializedName("MainObj")
public List<Key> Main;
public class Key {
#SerializedName("Key")
public String Key;
#SerializedName("code")
public String Code;
}
}
And change
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
by
String tmp = new Gson().toJson(new MainObj());

Categories