How to grab inner JSON map - java

Im trying to get specific values from the map.
I need to get value assigned to "leaguePoints", "tier", "rank", for
"queueType": "RANKED_SOLO_5x5" && "playerOrTeamName": "Invicterr".
I added code I try below.
I think I need to iterate entries:[], but I have no idea how to to this.
Im a total JSON newbie, and Java begginer.
Map:
"32303008": {
"queue": "RANKED_SOLO_5x5",
"name": "Sejuani's Berserkers",
"entries": [
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"miniSeries": {
"progress": "LWN",
"target": 2,
"losses": 1,
"timeLeftToPlayMillis": 0,
"wins": 1
},
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 0,
"playerOrTeamId": "21747474",
"leaguePoints": 100,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "sunchasee",
"wins": 127
},
{
"isHotStreak": false,
"isFreshBlood": false,
"leagueName": "Sejuani's Berserkers",
"isVeteran": false,
"tier": "PLATINUM",
"lastPlayed": 1389198358615,
"playerOrTeamId": "32303008",
"leaguePoints": 64,
"rank": "V",
"isInactive": false,
"queueType": "RANKED_SOLO_5x5",
"playerOrTeamName": "Invicterr",
"wins": 462
}
],
"tier": "PLATINUM"
}
My code:
for (Map.Entry<String, League> entry : leagues.entrySet())
{
try
{
if(Integer.parseInt(entry.getKey()) == 32303008)
{
System.out.println(entry.getKey() + "|" + entry.getValue());
}
}
catch(Exception e){}
}

I would recommend using something like JSON Simple. This will convert your JSON to a Java object that will be more simple to work with.

Pseudocode:
Map jsonMain = JSONParser.parse(myJSONSourceString);
Map numberedEntry = (Map)(jsonMain.get("3203008"));
List entries = (List)(numberedEntry.get("entries"));
for (int i = 0; i < entries.size(); i++) {
Map theEntry = (Map)(entries.get(0));
String queueType = (String)(theEntry.get("queueType"));
String playerOrTeamName = (String)(theEntry.get("playerOrTeamName"));
if (queueType.equals("RANKED_SOLO_5x5") && (playerOrTeamName.equals("Invicterr")) {
Number leaguePoints = (Number)(theEntry.get("leaguePoints"));
int leaguePointsValue = leaguePoints.intValue();
String tier = (String)(theEntry.get("tier"));
String rank = (String)(theEntry.get("rank"));
// Do something with the values
break;
}
}
The precise types and method names (and whether casting is needed) will depend on which JSON kit you use.

Related

JSON to Java: How to model lists of objects into generic model

I'm making a spreadSheet using SpreadJS, and I should be able to to add, delete and change the value of a key nested inside many objects. Here is how my json is formatted:
{
"version": "10.0.0",
"sheets": {
"Sheet1": {
"name": "Sheet1",
"data": {
"dataTable": {
"0": {
"0": {
"value": 129
}
}
}
},
"selections": {
"0": {
"row": 0,
"rowCount": 1,
"col": 0,
"colCount": 1
},
"length": 1
},
"theme": "Office",
"index": 0
}
}
}
The data represents, say, the value of each cell in the spreadSheet [0,0], [0,1], [1,1] ...etc. I want to parse this data into a List of generic model, for the field dataTable i would like to represent it like this: Map<Integer, Map<Integer, ValueObj>> for example in this case <0, <0, 129>> but i didn 't find how to do that and how my model would likely be.
I am new to JSON any help is appreciated! Thanks
Then to handle data, you can have a generic class like :
class CellData<T> {
T data;
}
Then read as below :
String jsonInput = "{ \"0\": { \"0\": { \"value\": 129 } } }";
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<Integer,HashMap<Integer,CellData<Integer>>>> typeRef =
new TypeReference<HashMap<Integer, HashMap<Integer, CellData<Integer>>>>() {};
Map<Integer, Map<Integer, CellData<Integer>>> map = mapper.readValue(jsonInput, typeRef);

How to set nested JSON data to datatables?

I have a (nested) data structure containing objects and arrays. And trying to sent datatables but only one value displaying.
JSON data:
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
JSON data getting through URL by using Java.
jQuery code:
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
Here it is possible to display either first or second list values by using list.1 or list.0
But I want two values at a time.
If you used render or mRender you can do what you want with the object. For example you can traverse the array like in this example.
$('#largeTable').DataTable({
"columnDefs": [
{"targets": [0], "title":"name", "data":"name"},
{"targets": [1], "title":"value", "data":"value"},
{"targets": [2], "title":"list", "data":"list", "type":"html"
"render":function(data){
var listArray = data;
var listHtml = "";
for(var i=0;i<listArray.length;i++) {
listHtml += listArray[i].sname + " " + listArray[i].svalue + "<br>";
}
return listHtml;
},
}]
});
$.ajax({
"type":"GET",
"url":url,
"success":function(data,status) {
var jsonData = $.parseJSON(data);
$('#largeTable').dataTable().fnAddData(jsonData);
}
Your list in json data structure is an array. So, you should use
list.forEach(function(element) {
//console.log(element);
});
You could create an object and build JSON dynamically and set it to "columns" array.
Here is an example:
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';

Issue In extracting desired data from the Json Response

My Json response looks like this:
{
"oAuthClientResponse": {
"grantTypes": [
"client_credentials",
"urn:ietf:params:oauth:grant-type:jwt-bearer"
],
"appId": "0e0da052-baab-4e86-a826-edfcaadbd93b",
"certAlias": "tenant_269869150664042.st2Oauth.st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT.cert",
"clientCertificate": "MIIC",
"paramList": null,
"audiences": [
"http://svc.com/EndPoint/st2/CommonApi::RW",
"http://svc.com/EndPoint/st2/CommonApi::RO"
],
"isDisabled": "false",
"clientMetadata": {
"isTenantManaged": "false",
"isTrusted": "true"
},
"activityData": {
"createdOn": "08/10/2015 02:15:55"
},
"tenant": "tenant_269869150664042",
"description": "st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT",
"name": "st2Oauth_svc_269869150693042_st2_client_OAUTHCLIENT",
"appSecret": "EghTRToAFJUWHrsnXlK5",
"clientType": "CONFIDENTIAL_CLIENT"
}
}
I want to read the value of audiences.
String value = jObject.getJSONObject("oAuthClientResponse").getString(
"audiences");
In value I am getting :
"audiences": [
"http://svc.com/EndPoint/st2/CommonApi::RW",
"http://svc.com/EndPoint/st2/CommonApi::RO"
]
Now I am not able to extract the value of the audiences.i.e.
http://svc.com/EndPoint/st2/CommonApi::RW and
http://svc.com/EndPoint/st2/CommonApi::RO
Kindly suggest.
Use getJSONArray() instead of getString()
JSONArray audiences = jObject.getJSONObject("oAuthClientResponse")
.getJSONArray("audiences");
Then you can retrieve the individual values using indices
System.out.println(audiences.getString(0)); // http://svc.com/EndPoint/st2/CommonApi::RW
System.out.println(audiences.getString(1)); // http://svc.com/EndPoint/st2/CommonApi::RO
String value = jObject.getJSONObject("oAuthClientResponse").getString(
"audiences");
value = value.subString(value.indexOf('['))
value = value.replace("[","");
value = value.replace("]","");
value = value.replace("\"","");
StringTokenizer stringTokenizer = new StringTokenizer(
actualOutput, ",");
while (stringTokenizer.hasMoreElements()) {
String value = (String) lineTokenizer.nextElement();
System.out.println(value)
}

Get sub-array from JSON

I parsing some data from a json file. Here is my JSON File.
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name values for each array with single query.
2) Can I get all those values in an Array ?
Please correct me, if I am doing anything wrong. Thank you.
Iteration cannot be avoided here as org.json and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects" unless you probably get a Json parser like Gson to unmarshall it that way.
But, that's too much to just avoid a for loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
Better to use a json parser such as GSon or Jackson to marshall your json to a java object. Then you can write utitlity method in your java class to retrieve all the names in that object.
Try this:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}

Parsing nested JSON

I have the following JSON:
{
"registration": {
"name": "Vik Kumar",
"first_name": "Vik",
"last_name": "Kumar",
"bloodGroup": "B-",
"gender": "male",
"birthday": "10\/31\/1983",
"email": "vik.ceo\u0040gmail.com",
"cellPhone": "1234123456",
"homePhone": "1234123457",
"officePhone": "1234123458",
"primaryAddress": "jdfjfgj",
"area": "jfdjdfj",
"location": {
"name": "Redwood Shores, California",
"id": 103107903062719
},
"subscribe": true,
"eyePledge": false,
"reference": "fgfgfgfg"
}
}
I am using the following code to parse it:
JsonNode json = new ObjectMapper().readTree(jsonString);
JsonNode registration_fields = json.get("registration");
Iterator<String> fieldNames = registration_fields.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
String fieldValue = registration_fields.get(fieldName).asText();
System.out.println(fieldName+" : "+fieldValue);
}
This works fine and it print all the values except for location which is kind of another level of nesting. I tried the same trick as above code to pass json.get("location") but that does not work. Please suggest how to make it work for location.
You need to detect when you are dealing with a (nested) Object using JsonNode#isObject:
public static void printAll(JsonNode node) {
Iterator<String> fieldNames = node.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
if (fieldValue.isObject()) {
System.out.println(fieldName + " :");
printAll(fieldValue);
} else {
String value = fieldValue.asText();
System.out.println(fieldName + " : " + value);
}
}
}
Thus, when you reach an object, such as location, you'll call the printAll recursively to print all its inner values.
org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString);
org.codehaus.jackson.JsonNode registration_fields = json.get("registration");
printAll(registration_fields);
Since location is nested within registration, you need to use:
registration_fields.get("location");
to get it. But isn't it already processed by the while-loop, why do you need to get it separately?

Categories