How to Extract JSON value outside of Array - java

At the moment I can loop through my JSON array ''pos" and store all the variables within that into a array list.
What I'm trying to do:
How can I easily parse tour & date which are outside the "pos" array?
I would like to store the values in "tour" & "date" into two separate string variables.
My understanding: json.getJSONArray() can't be used in this case, as json.getJSONArray(TAG_MESSAGES); only pulls in "pos" array data.
JSON Structure:
{
"pos": [
{
"pos": "",
"person": "",
"thur": "",
"score": "",
"round": ""
},
{
"pos": "2",
"person": "John",
"thur": "",
"score": "16",
"round": "3"
},
{
"pos": "3",
"person": "Peter Lynch",
"thur": "",
"score": "5",
"round": "2"
}
],
"tour": "Camping",
"date": "Thursday Jul 23 - Sunday Jul 26, 2015"
}
Code to Parse JSON pos array:
// ALL JSON nodes
private static final String TAG_MESSAGES = "pos";
private static final String TAG_ID = "pos";
private static final String TAG_FROM = "person";
private static final String TAG_EMAIL = "thur";
private static final String TAG_SUBJECT = "round";
private static final String TAG_DATE = "score";
// These are outside of array pos
private static final String TAG_TOUR = "tour";
private static final String TAG_TOURDATE = "date";
try {
inbox = json.getJSONArray(TAG_MESSAGES);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++) {
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, from);
map.put(TAG_EMAIL, mailer);
map.put(TAG_DATE, date);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
inboxList.add(map);

as you can get a JSONArray from your json , you can get String from it too.
something like this :
json.getString("tour");
json.getString("date");

Try this,
String tour = "", date = "";
try {
if(json.has("tour"))
tour= json.getString("tour");
if(json.has("date"))
date= json.getString("date");
} Catch(Exception e) {
}
Which will not crash even if there is no date/ tour key(if missing)

inbox = json.getJSONArray(TAG_MESSAGES);
String tour=json.getString("tour");
String date=json.getString("date");

Related

Java - Read data from a json with the JSON library according to an object

I have a JSON with some data and I would like to print as follows
10 REGISTER 1, KP SUM 2081,606
20 REGISTER 2 CH SUM 0,22
Where the general sum is calculated by the total sum of the items according to the code.
Following the rule, first multiply the quantity by the unit and then add all the items that have the same code.
Example:
code 10
SUM = 0,0200000 * 7,40 + 10,0000000 * 200,31 + 0,5690000 * 40,19 + 0,7890000 * 70,33
The same goes for the other codes that appear in JSON
My JSON
[
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"itemCode": 1,
"descriptionItem": "ITEM",
"unityItem": "UN",
"quantity": "0,0200000",
"valueUnity": "7,40"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "UN",
"quantity": "10,0000000",
"valueUnity": "200,31"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88248,
"descriptionItem": "ITEM 3",
"unityItem": "H",
"quantity": "0,5690000",
"valueUnity": "40,19"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88267,
"descriptionItem": "ITEM 4",
"unityItem": "N",
"quantity": "0,7890000",
"valueUnity": "70,33"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 1,
"descriptionItem": "ITEM 1",
"unityItem": "H",
"quantity": "30,0000000",
"valueUnity": "0,17"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "H",
"quantity": "3,0000000",
"valueUnity": "0,07"
}
]
My class Java
public class MyJson {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("description")
#Expose
private String description;
#SerializedName("unity")
#Expose
private String unity;
#SerializedName("typeItem")
#Expose
private String typeItem;
#SerializedName("codeItem")
#Expose
private Integer codeItem;
#SerializedName("descriptionItem")
#Expose
private String descriptionItem;
#SerializedName("unityItem")
#Expose
private String unityItem;
#SerializedName("quantity")
#Expose
private String quantity;
#SerializedName("valueUnity")
#Expose
private String valueUnity;
private Double total;
}
My Program
public static void main(String[] args) {
Gson gson = new Gson();
try {
File jsonFile = new File("C:\\my_json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
MyJson[] myJsonArray = gson.fromJson(jsonBuffer, MyJson[].class);
BigDecimal valueUnity = BigDecimal.ZERO;
BigDecimal sumTotal = BigDecimal.ZERO;
//
Set<MyJson> list = new HashSet<>();
for(MyJson myJson : myJsonArray) {
if(checkStringNullOrEmpty(myJson.getQuantity()) && checkStringNullOrEmpty(myJson.getValueUnity())) {
if(myJson.getCode().equals(myJson.getCode())) {
String value1 = myJson.getQuantity().replaceAll( "," , "." ).trim();
String value2 = myJson.getValueUnity.replaceAll( "," , "." ).trim();
BigDecimal quantity = new BigDecimal(value1);
BigDecimal valueUnit = new BigDecimal(value2);
valueUnity = quantity.multiply(valueUnit);
somaTotal = sumTotal.add(valueUnity);
String resultado = String.format(Locale.getDefault(), "%.2f", valueUnity);
String sumTotal2 = String.format(Locale.getDefault(), "%.2f", sumTotal);
myJson.setTotal(new Double(sumTotal2.replaceAll( "," , "." ).trim()));
list.add(myJson);
}
}
}
for(MyJson myJson : list) {
StringBuilder builer = new StringBuilder();
builer.append(myJson.getCode()).append(" ");
builer.append(myJson.getDescription().toUpperCase()).append(" ");
builer.append(myJson.getUnity().toUpperCase()).append(" ");
builer.append(myJson.getTotal());
System.out.println(builer.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkStringNullOrEmpty(String value) {
if(!value.isEmpty()) {
return true;
} else {
return false;
}
}
Exit program
The calculation is being done wrong when using the Set
10 REGISTER 1, KP SUM 130,33
20 REGISTER 2 CH SUM 439,18
You cannot keep track of multiple running totals (i.e. one for each code) using one total. Instead you will need one total for each different code.
I would recommend that you use a Map<Integer, MyJson> for this purpose. This would store a number of MyJson objects which you could look up by their code. When handling each MyJson object, you check to see if you already have a MyJson object with the same code: if you do then you add to its total, otherwise you add your MyJson object to the map.
Get rid of your Set<MyJson> variable (which you have somewhat confusingly named list) and replace it with the following
Map<Integer, MyJson> jsonsByCode = new LinkedHashMap<>();
(You can use a HashMap<> instead of a LinkedHashMap<> here: I chose to use a LinkedHashMap<> because it keeps its entries in the same order they were inserted into it.)
Then, replace all lines from somaTotal = sumTotal.add(valueUnity); to list.add(myJson); with
if (jsonsByCode.containsKey(myJson.getCode())) {
// We've seen this code before, so add the value
// to the total.
MyJson matchingJson = jsonsByCode.get(myJson.getCode());
matchingJson.setTotal(matchingJson.getTotal() + valueUnity.doubleValue());
} else {
// First time seeing this code, so set its total
// and add it to the map.
myJson.setTotal(valueUnity.doubleValue());
jsonsByCode.put(myJson.getCode(), myJson);
}
(Note that BigDecimal values such as valueUnity have a .doubleValue() method on them, which is the easiest way to convert them to a double.)
Then, in the for loop below, where you are printing out the values, replace list with jsonsByCode.values().
I made these changes to your program and it generated the following output:
10 REGISTER 1 KP 2081.60648
20 REGISTER 2 CH 5.31
Incidentally, your code also contains the following if statement:
if(myJson.getCode().equals(myJson.getCode())) {
// ....
}
You are comparing myJson.getCode() against itself, so this condition will always be true (unless of course myJson.getCode() returns null, in which case you get a NullPointerException). You can just get rid of this check, it doesn't do anything useful.

how to access array list and validate the value with AND conditions

I got the response as follow:
{
"cartId": "default",
"cartLines": [
{
"testid": "123",
"isDeleted": false,
"name": "peter",
},
{
"testid": "123",
"isDeleted": true,
"name": "mary",
}
],
"type": "test"
}
I would like to make sure the value of "name": "peter"
when query condition is "testid": "123" AND "isDeleted": false
what class can i use? Either java or groovy scripting language is good.
this is the usual way i did assertion, straightforward. the println(test_info) returned response i gave at above.
now i wanted to use for more conditions.
//SQL statement
String dbQuery2 = /SELECT * FROM public.tests where test_id = 'default'/
//Connect to PostgresSQL, global variable is stored at profile
List results = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.dbConnString2 , GlobalVariable.dbUsername2 , GlobalVariable.dbPassword2 ,GlobalVariable.dbDriver2 ,dbQuery2 )
println(results)
//print the "test_info" column
String test_info = results.get(0).get('test_info')
println(test_info)
//convert to json format and verify result
def test_infojson = new JsonSlurper().parseText(new String(test_info))
println('Database test_info response text: \n' + JsonOutput.prettyPrint(JsonOutput.toJson(test_infojson)))
assert test_info.contains("peter")
The below solution is in java:
You need have a class to represent your JSON structure.
class Response {
String cardId;
String type;
List<Cartline> cartlines;
//Constructor
//Getters and Setters
}
class Cartline {
String name;
String testid;
boolean isDeleted;
//Constructor
//Getters and Setters
}
Then in your main code, you can do as shown below:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("cartLines");
for (int i = 0; i < arr.length(); i++)
{
String name = arr.getJSONObject(i).getString("name");
String testId = arr.getJSONObject(i).getString("testId");
Boolean isDeleted = arr.getJSONObject(i).getBoolean("isDeleted");
if (name.equals("peter") && testId. equals("123") && isDeleted == false) {
// do your stuff
}
}
You can access the jar file here : http://mvnrepository.com/artifact/org.json/json

Read the all value presents in Hashmap

I have define List of HashMap and reading the response of JSON API . Currently able to read only one value from the list and I want to read all the values.
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("country");
System.out.println(a);
JSON Response in PostMan
{
"response": {
"code": 200,
"status": "success",
"alert": [
{
"message": "Success",
"type": "success",
"skippable": 1
}
],
"from_cache": 0,
"is_data": 1
},
"data": [
{
"id": 6004,
"airport_name": "Adampur Airport",
"city": "Adampur",
"country": "India",
"iata": "AIP",
"icao": "VIAX",
"latitude": "31.4338",
"longitude": "75.758797",
"altitude": "775"
}
]
}
Just forEach on your List you will get Map and then get all your Object bu using get .
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
allids.forEach(elem->{
String country = (String) elem.get("country");
String city = (String) elem.get("city");
// and so on.
});
Judging from the context, you can iterate over the list and get the Map values
List<HashMap<String,Object>> allids = response.jsonPath().getList("data");
for(int i=0; i<allids.size(); i++){
HashMap<String,Object> firstid = allids.get(i);
String country = (String) firstid.get("country");
String city = (String) firstid.get("city");
String iata = (String) firstid.get("iata");
String altitude = (String) firstid.get("altitude");
//similarly get others
System.out.println(country);
}

Parse JSON File and iterate over specific parameters

where I want to check which elements of the 1st file are missing in the second one.
Here is the form of the first one:
[
{
"pId": "pId1",
"Platform":["ios","and","web","winph","win"],
"Name": "ay",
"ShortDescription": "Mobi",
"Detail" : {
"IncentiveInformation": "ppp",
"DisplayName" : "vvv!",
"Description" : "mmm",
"TermsAndConditions": ".."
}
},
{
"pId": "pId2",
"Platform":["afasd","sdfsd","pppp","asdas","win"],
"Name": "ay",
"ShortDescription": "mob",
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:01","2015.01.01-23:59"],
"IncentiveInformation": "PRO",
"Name": "iTunes",
"ShortDescription": "Punkte sammeln bei iTunes",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "urlHere",
"JumpToShopName" : "Zu iTunes"
}
},
{
"pId": "pId3",
"Platform":["wqdsa"],
"Name": "poti",
"ShortDescription": "pun",
"ImageURL": "url.here",
"Promotion" : false,
"PromotionDetail": {
"DebugMode": false,
"PromoDate": ["2015.01.01-00:00","2015.01.01-23:59"],
"IncentiveInformation": "ppeur",
"Name": "namehere",
"ShortDescription": "tune",
"DisplayName": null,
"Description": null,
"ImageURL": null,
"JumpToShopURL": "noq",
"JumpToShopName" : "Zu"
}
}
]
and here is the form of the 2nd one:
{
"pList": [{
"shortName": "bb",
"longName": "bb",
"pId": "pId2",
"featured": true,
"pLog": "url.here",
"incentivation": "eu",
"details": {
"teaserImage": "image.url",
"description": "desc here",
"jumpToShopURL": "nurl",
"jumpToShopButton": "zubay",
"terms": [{
"headline": "Wichtig",
"body": "bodyline"
}]
}
}, {
"shortName": "one short name",
"longName": "bkp",
"pId": "pId1",
"featured": true,
"pLo": "some.pLo",
"incentivation": "1p",
"details": {
"teaserImage": "some.url",
"description": "desc",
"jumpToShopURL": "short url",
"jumpToShopButton": "Zuay",
"terms": [{
"headline": "Wichtig",
"body": "bodyhere"
}]
}
}]
}
Si I thought to save all the "pId" of the first one in a List(or array) and then iterate over that list and check for each one if the pId exists in the new one.
So I tried this, but it is not working..
Could anyone help me with that? I tried a bit and then I found that I have too many difficulties, to get the pIds saved in a list or an array.
So has someone an idea?
import java.io.*;
import org.json.*;
public class MainDriver {
public static void main(String[] args) throws JSONException {
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONObject jobj = new JSONObject(jsonData);
JSONArray jarr = new JSONArray(jobj.getJSONArray("pList").toString());
for(int i = 0; i < jarr.length(); i++)
System.out.println("id: " + jarr.getString(i));
}
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
For the 2nd form, you have an JSONObject, but it contains some errors. Please fix them, or use a the 1st form again.
SOLUTION
I found some errors in the second file so I suggest the following edits:
change "jumpToShopURL": nurl", to "jumpToShopURL": null,
add a comma at the end of "description": "desc"
add a comma at the end of "jumpToShopURL": "short url"
For the code, you can use the following lines:
/*first file*/
String jsonData = readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt.json");
JSONArray jarr = new JSONArray(jsonData);
/*array of first file's ids*/
ArrayList<String> srcArray = new ArrayList<>();
for(int i = 0; i < jarr.length(); i++) {
srcArray.add(jarr.getJSONObject(i).getString("pId"));
}
/*second file*/
// second form in a seperate file
JSONObject obj = new JSONObject(readFile("C:\\Users\\kbelkhiria\\Desktop\\Karim_JSON\\alt2.json"));
JSONArray arr = obj.getJSONArray("pList");
/*array of second file's ids*/
ArrayList<String> dstArray = new ArrayList<>();
for(int i = 0; i < arr.length(); i++) {
dstArray.add(jarr.getJSONObject(i).getString("pId"));
}
for (String string : srcArray) {
if (dstArray.indexOf(string)==-1)
System.out.println(string + " is missing in the second file");
}
Luckily for you there are already developed libraries to parse any JSON string, like the one's you provided. One of the most popular is
org.json
Using this you can write code similar to this:
import org.json.*;
String myString = ".." // The String representation you provided
JSONObject obj = new JSONObject(myString);
JSONArray arr = obj.getJSONArray("pList");
Another popular library for the same task is GSON
One possible solution using Jackson is the following:
private static final String JSON1 = // first json;
private static final String JSON2 = //second json;
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<LinkedHashMap> list1 = Arrays.asList(mapper.readValue(JSON1, LinkedHashMap[].class));
List<LinkedHashMap> list2 = Arrays.asList(mapper.readValue(mapper.readTree(JSON2).get("pList").toString(), LinkedHashMap[].class));
List<LinkedHashMap> missingItens = new ArrayList<>();
for (LinkedHashMap o1 : list1) {
if (!objectExistsInList(o1.get("pId").toString(), list2)) {
missingItens.add(o1);
}
}
}
private static boolean objectExistsInList(String pIdValue, List<LinkedHashMap> objs) {
for (LinkedHashMap map : objs) {
if (map.containsValue(pIdValue)) {
return true;
}
}
return false;
}
Please keep in mind this is a very specific implementation to the given JSONs.

Parsing a JSON object within a JSON object

I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));

Categories