iterate over .json file and print all values in JAVA [duplicate] - java

This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 2 years ago.
this is a prices.json file which contains many products prices
i need iterate over this .json in order to compare with another json output from another system
i need to get only the fields
"MATNR" field which contains the product ID
and
"NET_PRICE" = contain the price before VAT
and
"PRICE_INC_TAX" = contain the price after VAT
[
{
"customer": {
"AUART": "",
"KALSM": "ZDPS00",
"KUNNR": "0001234567",
"SPRAS": "",
"VKGRP": "",
"VKORG": "1000",
"VTWEG": "10",
"ZMDD": "99",
"ZTERM": ""
},
"outdated": false,
"outputs": [
{
"KUNNR": "0001234567",
"KWMENG": "1",
"MATNR": "000000000001000001",
"NET_PRICE": "15.50",
"NET_PRICE_PER_BASE_UNIT": "15.50",
"ORDER": "1",
"PRICE_INC_TAX": "18.13",
"PRICE_INC_TAX_PER_BASE_UNIT": "18.13",
"TOTAL_TIME": "Total Calculation Time: 15ms",
"VRKME": "EA",
"converted_quantity": "1.00"
},
{
"KUNNR": "0001234567",
"KWMENG": "1",
"MATNR": "000000000001000002",
"NET_PRICE": "20.00",
"NET_PRICE_PER_BASE_UNIT": "20.00",
"ORDER": "1",
"PRICE_INC_TAX": "23.40",
"PRICE_INC_TAX_PER_BASE_UNIT": "23.40",
"TOTAL_TIME": "Total Calculation Time: 12ms",
"VRKME": "EA",
"converted_quantity": "1.00"
},
{
"KUNNR": "0001234567",
"KWMENG": "1",
"MATNR": "000000000001000003",
"NET_PRICE": "20.00",
"NET_PRICE_PER_BASE_UNIT": "21.00",
"ORDER": "1",
"PRICE_INC_TAX": "24.40",
"PRICE_INC_TAX_PER_BASE_UNIT": "24.40",
"TOTAL_TIME": "Total Calculation Time: 12ms",
"VRKME": "EA",
"converted_quantity": "1.00"
}
]
}
]
this is the block of code I'm trying get the specific values but it's still not works:
public static void parseJson() {
JSONParser jsonP = new JSONParser();
try (FileReader reader = new FileReader("MyJson.json")) {
// Read JSON File
Object obj = jsonP.parse(reader);
JSONArray priceList = ((JSONArray) obj).get("outputs");
//1) getting error above line "The method get(int) in the type ArrayList is not applicable for the arguments (String)"
//2) TODO: here I want to iterate only the "MATNR", "NET_PRICE", PRICE_INC_TAX values
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
I'll be so thankful who can solve me two questions on this method!
Thanks in advance

We use the javax.json.* library for doing that kind of stuff.
try(JsonReader jsonReader = Json.createReader(new StringReader(myJsonString))) {
JsonObject jsonObject = jsonReader.readObject();
return jsonObject.getJsonArray("outputs");
// TODO: don't return something, instead iterate over array and get attributes from objects.
}
catch(Exception exception) {
// TODO: Do something with exception
}
I hope that helps.

Related

Not sure why it has to say not valid Json after replacing the values of paymentKey and Session key

I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.

Add new entry to the json file which has dup key

data.json , please note dup key city
{
"type": "1",
"city": [
{
"name": "c1",
"dis": [
{
"dis_name": "d1"
},
{
"dis_name": "d2"
}
]
}
],
"city": [
{
"name": "c2",
"dis": [
{
"dis_name": "d3"
},
{
"dis_name": "d2"
}
]
}
]
}
I think, because of dup key, JSON object built from the file is incorrect or has partial data.
JSONObject obj = new JSONObject(readJSONFromAsset());
readJSONFromAsset() copied from stackoverflow,
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
return json;
}
in obj, I see only partial data of json file. What is the best way to add following new entry in json file/object?
"city": [
{
"name": "c3",
"dis": [
{
"dis_name": "d5"
},
{
"dis_name": "d2"
}
]
}
]
That's not a valid json document. Valid json cannot have duplicate keys. What happens when you try to treat it as JSON depends on how your deserializer chooses to implement it- it could throw an exception, keep the first, or keep the last as common choices.
The only answer which will work is to fix your data so it is a valid json document. I'd suggest turning city into an array.

get json data based on object name

May be it's a simple task for some one.
I've json like below.
{
"address": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"address2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"address3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
},
"valid": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"valid2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"valid3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
}
}
This is a sample structure. Some times may have many objects inside of one object. I know this is a bad format of JSON but i've to achieve my requirement by using this only :-(.
My requirement is: when we sending the object name like address3 or valid3 to a method as argument. My method have to return key and value of object (Which we passed as argument). Any one know, how to achieve this in Java?
You can parse the JSON and convert the result into a HashMap<String,String>
Here is sample code for this JSON object .
public HashMap<String,String> getKeyValuePairs(JSONObject json,String key){
HashMap<String,String> jsonHashList=new HashMap<String,String>();
JSONObject desiredJSON = json.get(key);
Iterator<?> keys = desiredJSON.keys();
while( keys.hasNext() ) {
String key2 = (String)keys.next();
if ( desiredJSON.get(key2) instanceof JSONObject ) {
String value = desiredJSON.get(key2);
jsonHashList.add(key2,value);
}
}
return jsonHashList;
}
Note : In this case key is assumed to be at level one of passed JSON so if you want to pass any JSON to get it's key values separated pass the Level One JSON.
This is the solution
private void parseJson(JSONObject jsonObject, String objName){
try {
for(int i = 0; i < jsonObject.length(); i++){
if(jsonObject.get(jsonObject.names().getString(i)) instanceof JSONObject){
JSONObject singleObj = new JSONObject(jsonObject.get(jsonObject.names().getString(i)).toString());
Iterator<String> keys= singleObj.keys();
while (keys.hasNext()){
String keyValue = keys.next();
final String valueString = singleObj.getString(keyValue);
if(!isJSONObjectOrString(valueString)){
if(keyValue.contains(objName) || valueString.contains(objName)
|| jsonObject.names().getString(i).contains(objName)){
Log.e("objectName", jsonObject.names().getString(i));
Log.e(keyValue, valueString);
}
}
}
parseJson(singleObj);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

"No value for" exception for getJSONArray

I have a JSON object like this :
{
"Successful": true,
"Value": {
"Materials":[{
"MaterialID": 37628,
"MaterialID": 0,
"MaterialNo": 26868,
"Type": 0,
"MaterialName": Copper
}],
"Prices": []
}
}
I'm trying to get materials array like this :
public ArrayList<Material> parseMaterial (JSONObject object)
{
try
{
JSONArray materialArray = object.getJSONArray("Materials");
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMaterial", e.getMessage());
}
}
I get this exception :
JSONParser=>parseMaterial﹕ No value for Materials
Can you tell me what is wrong with the code? Thanks.
You're missing a step: change
JSONArray materialArray = object.getJSONArray("Materials");
to
JSONObject value = object.getJSONObject("Value");
JSONArray materialArray = value.getJSONArray("Materials");
getJSONArray does not 'search' the entire object (this could give unpredictable results if you have multiple Materials in the object), only the first level.

JSON parsing Issues Redux

I had issues in the past with parsing my JSON code, and I almost had it and lost all my code changes. I am putting here the guts of it getting my JSON (which I have verified it gets fine). It's just the parsing of it...I need to get the "fulltext" field and I guess put it into an array...
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag" , "Error converting result " + e.toString());
}
try{
JSONObject rootobject = new JSONObject(result).getJSONObject("query").getJSONObject("results");
} catch (JSONException e){
Log.e("JSON Parser", Log.getStackTraceString(e));
e.printStackTrace();
}
return null;
Within this, the JSONObject area I believe is incorrect. I need to iterate over all of the JSON objects getting the "fulltext" value from all of them and eventually putting them into the database. I'm drawing the team names from this website.
In my mind, I should be able to use
String teamname = rootobject.getString("fulltext");
in some way. I have tried this, but it doesn't work at all. In fact I get the error message "No value for fulltext" when I check the error logs.
I know I'm going wrong somewhere but can't quite place it. I'm still confused with JSON parsing and whatnot but I'm determined to get there.
This is a link to the sample JSON (the URL that I'm accessing)
http://bit.ly/1JnlSck
My apologies for forgetting this in the first post.
What you probably should do is restructure your JSON. Currently you have it like this...
"results": {
"Team:\"Die Unglaublichen\"": {
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
"Team:(Can't Stand) Le Kubb Bricks": {
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
}
... where "results" is a JSONObject containing several child JSONObjects. If you can rework it so that "results" is a JSONArray containing JSONObjects, like so...
"results": [
{
"Team": "Die Unglaublichen",
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
{
"Team": "(Can't Stand) Le Kubb Bricks",
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
]
... then you can loop through the "results" array and get each of its JSONObjects and any name/values you wish:
try {
JSONArray resultsArray = rootObject.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject teamObject = resultsArray.getJSONObject(i);
String fullText = teamObject.getString("fulltext");
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories