How to find a key in a JSON file with Gson library? - java

Given a JSON file which looks like the code below, how can I find a specific key with its corresponding value without hard-coding the structure in a Java class or otherwise. Let's say I want to get "Signal_Settings" as a JSON Object but given the possibility of changes in the JSON file structure I want to get this object regardless for example by iterating through all keys in the file. I have tried to do this iteratively and failed, so I think a recursive function is the way for which I didn't find a solution yet. My iterative code looks like this:
while (true) {
try {
for(Map.Entry<String, JsonElement> entry:newJsonObj.entrySet()){
System.out.println(entry.getKey());
System.out.println("Before NewJsonObj:" + newJsonObj);
newJsonObj = newJsonObj.getAsJsonObject(entry.getKey());
System.out.println("After NewJsonObj:" + newJsonObj + "\n");
//tempEntrySet = newJsonObj.entrySet().iterator().next();
}
//System.out.println("Key:" + tempEntrySet.getKey());
//System.out.println("TempEntry:" + tempEntrySet);
}catch (Exception e){
break;
}
}
and the JSON file:
{
"config2": {
"UDP_Settings": {
"ListenAddress": "'127.0.0.1'",
"ListenPort": "54523"
},
"Signal_Settings": {
"Count": 1,
"Signals": [
{
"Name": "time",
"Type": "uint8",
"Interval": "foo",
"Description": "",
"Unit": null
},
{
"Name": "othersignal",
"Type": "uint8",
"Interval": "fff",
"Description": "",
"Unit": null
}
]
},
"Tag_Settings": null,
"Model_Settings": null
}
}

Related

How to assign to a new array an array of objects?

I can't figure out how I would do the ff.
I have the ff. Payload
{
"code": null,
"message": null,
"recCtrlOut": {
},
"acctSumm": [
{
"acctBasic": {
"acctType": "SV",
"acctId": "123",
},
"acctBasic": {
"acctType": "SV",
"acctId": "321",
}
}
]
}
And I just want to get the acctId params and assign it to a new plain array of accountIds. How do I do it in Spring/Java?. Thanks
Try using json path. Library can be found here. E.g. say you had json like this:
{
"code": null,
"message": null,
"recCtrlOut": {
},
"acctSumm": [
{
"acctBasic": {
"acctType": "SV",
"acctId": "123"
}
},
{
"acctBasic": {
"acctType": "SV",
"acctId": "321"
}
}
]
}
Actual code would be something like:
List<String> ids = JsonPath.read(json, "$.acctSumm[*].acctBasic.acctId");
The above list will now hold:
["123","321"]
If you wanna learn json path syntax, you could try using this online tool. Here is also a guide to help you get started with json path.

How to populate velocity string with a JSON Object in JAVA?

I am working on velocty and java, I was to take values from an json file (which I took using recursion of JSON OBjects and storing path of recursion(See context below to get idea)
String hhh="I am a ${root.primaryApplicant.firstName} ${firstName} ";
Velocity.init();
VelocityContext vm=new VelocityContext();
for(String m : mp.keySet())
{
vm.put(m,mp.get(m));
}
StringWriter w = new StringWriter();
Velocity.evaluate( vm, w, "mystring", forma );
The map mp is obtained from a json file
{
"id": 45288,
"code": null,
"name": null,
"external": false,
"leadReferenceId": "APPID1573716175142",
"createdBy": null,
"createdDate": "2017-10-26T12:14:17.000Z",
"agentName": null,
"ipAddress": null,
"applicationType": "HOME",
"loanType": "HOME",
"applicantType": {
"id": 269,
"code": "Single",
"name": "Single",
"external": false
},
"relationship": null,
"primaryApplicant": {
"id": 45289,
"code": null,
"name": null,
"external": false,
"existingCustomer": null,
"customerId": null,
"partyRoleType": {
"id": 348,
"code": "0",
"name": "PRIMARY",
"external": false
},
"partyRelationshipType": null,
"salutation": {
"id": 289,
"code": "MR",
"name": "Mr",
"external": false
},
"firstName": "Anuj",
"middleName": "",
"lastName": "singh",
"dateOfBirth": "1986-12-11T18:30:00.000Z",
"genderType": {
using a debugger the context of vm contains
"root.primaryApplicant.firstName" -> "Anuj"
"firstName" -> "Anuj"
after Velocity evaluate I get
"I am a ${root.primaryApplicant.firstName} Anuj ";
i am assuming it cant replace keys with . in between.
Is there any better way to populate the string
----------------
The velocity file has a "root.*" specified and since I cant edit those, I am using the following recursion program to get the keys
private static void rexuse(String a,Map<String, Object> mp,JSONObject js,String parent) throws JSONException {
Iterator<String> keys = js.keys();
while(keys.hasNext()) {
String key = keys.next();
if(key.equals("name"))
{
mp.put(parent,js.get(key));
}
if (js.get(key) instanceof JSONObject) {
rexuse(a+"."+key,mp,js.getJSONObject(key),key);
}
else
{
if(!mp.containsKey(key) ||( mp.containsKey(key) && mp.get(key)==null))
mp.put(key, js.get(key));
mp.put(a+"."+key, js.get(key) );
}
}
}
where a is the prefix and called the above using
String a="root";
rexuse(a,mp,js,"root");
There is an inconsistency, here.
With the Java initialization code you give, the Velocity template should contain:
${primaryApplicant.firstName}
If you want to use ${root.primaryApplicant.firstName}, then the other reference should also be prefixed by root, as in ${root.firstName}, and the Java context initialization code should be:
vm.put("root", mp);
But in both cases you must also check that the json library you are using provides a Json object with a generic getter, so that the 'dot' operator will recursively call the Java method get(<fieldname>) on the json object. There are tons of those.

Iterate last values present in a JSON response using java

I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}

parse json object from json array in java using com.fasterxml.jackson.databind.JsonNode;

I am trying to parse some json which is a groupd of objects within an array. I am not fluent with java and having a hard time figuring out how to do this.
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
JsonNode messageNode = mapper.readTree(post);
if (!messageNode.isArray()){
try {
throw new Exception("INVALID JSON");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<String> listObjects = null;
JsonParser parser = mapper.getFactory().createParser(post);
the json format:
{
"data": [
{
"id": "897569693587466_897626706915098",
"from": {
"id": "1809583315",
"name": "Lena Cann Jordan"
},
"message": "Amen.",
"can_remove": false,
"created_time": "2014-11-11T22:41:11+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897627376915031",
"from": {
"id": "1776031725",
"name": "Kyla Munford"
},
"message": "Tell me what my God can't do!!!",
"can_remove": false,
"created_time": "2014-11-11T22:42:51+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897631636914605",
"from": {
"id": "100000106496788",
"name": "Sarah Barklow Tyson"
},
"message": "That's bc God is awesome!! He can give or take away!! \ud83d\ude4f\u2795",
"can_remove": false,
"created_time": "2014-11-11T22:49:46+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpVMk1USXdNalExTkRrd09qRTBNVFUzTkRrNU5qTTZOREE9",
"before": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpJMk56QTJPVEUxTURrNE9qRTBNVFUzTkRVMk56RTZNelU9"
},
"previous": "some link"
}
}
This is the json from the facebook graph api. I also need to extract the cursors and links below so would they also appear as one of the objects.
Appreciate advice.
Thanks
I think the real question is what you are trying to achieve? You are already parsing JSON into a tree model (JsonNode), and from that point on you can traverse content freely, using methods get, path and at (which uses JSON Pointer expression).
Or, as suggested by Samwise above, could consider modeling Java classes with same structure as JSON, so that you would have even easier time accessing data as regular Java objects. If so, you'd parse it simply by:
Graph graph = mapper.readValue(post);
Data d = graph.getData().get(0); // for first entry in "data" List

Unable to get specific data from a JSON object

I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Categories

Resources