Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic way of parsing Json in Java?

I have tried with gson and Jackson parsers unfortunately I couldn't achieve what I wanted to.

{
   "rateName": "My Special Rate",
   "adjustments":    [
            {
         "adjustmentType": "LOAN_AMOUNT_GREATER_THAN_550K",
         "rate": 0.75
      },
            {
         "adjustmentType": "AMORTIZATION_TERM_LESS_THAN_30_YEARS",
         "rate": -0.2
      }
   ],
   "errorTypes": [],
   "premiumTaxs": [],
   "renewalPremiums": [],
   "totalInitialRate": 1.95,
   "optimumPricing": false,
   "miPricingVO": null,
   "rateCardId": "BALS_NR",
   "ratingInfoBaseRate": 1.4
}

Above is the Json I want to parse. I want to create generic methods using which I can access a value by name easily. For example:

  1. getName(rateName) - Should return 'My Special Rate'
  2. getNameFromArray(adjustmentType, adjustments) - Should return 'LOAN_AMOUNT_GREATER_THAN_550K'

Is there a way to do this? It should be generic so that this can be applied on any Json file.

Additional info: I tried using Gson, but this parses the whole file and throws an error if it finds an array.

JsonReader j = new JsonReader(new FileReader("Path of Json"));
        j.beginObject();
        while (j.hasNext()) {
            String name = j.nextName();

            if (name.equals("rateName")) {
                System.out.println(j.nextString());
            }
            System.out.println(name);
        }

I tried with jackson and encountered the same as Gson.

JsonFactory jfactory = new JsonFactory();
        JsonParser jParser = jfactory.createJsonParser("Path of Json");
        while (jParser.nextToken() != JsonToken.END_OBJECT) {
            System.out.println(jParser.getCurrentName());;
        }
like image 496
Mike Avatar asked Feb 11 '23 19:02

Mike


2 Answers

If you mean standard library when you say generic, then org.json would be that library.

Altough not as intuitive as GSON or Jackson, it is easy to use it:

JSONObject jsonData = new JSONObject(jsonString);
String rateName= jsonData.getString("rateName");//My Special Rate

To parse array you need to loop:

JSONArray adjustments = jsonData.getJSONArray("adjustments");
for(int i = 0; i < adjustments.length(); i++){
   JSONObject adjustment = adjustments.getJSONObject(i);
   String adjustmentType = adjustment.getString("adjustmentType");
}
like image 172
meda Avatar answered Feb 14 '23 09:02

meda


Hi You can use JASON READER , it readers the JSON and map the data into a MAP .

Below is the URL to Download the JAR JASON READER.

https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU

Below is the example -

package com;



     import java.util.HashMap;
        import java.util.Map;
        import java.util.Map.Entry;

        import com.JasonReader;

        public class Test {

            public static void main(String[] args) {

            String request ="{\"rateName\": \"My Special Rate\",\"adjustments\":[{\"adjustmentType\": \"LOAN_AMOUNT_GREATER_THAN_550K\",\"rate\": 0.75},{\"adjustmentType\": \"AMORTIZATION_TERM_LESS_THAN_30_YEARS\",\"rate\": -0.2}],\"errorTypes\": [],\"premiumTaxs\": [],\"renewalPremiums\": [],\"totalInitialRate\": 1.95,\"optimumPricing\": false,\"miPricingVO\": null,\"rateCardId\": \"BALS_NR\",\"ratingInfoBaseRate\": 1.}";

                        //
                Map<String,String> map =new HashMap<String,String>();
                map=JasonReader.readJason(request,map);
                //System.out.println(map);
                for (Entry<String, String> entry : map.entrySet()) {
                    System.out.println(entry.getKey()+ "=" +entry.getValue());

                }
            }
        }

OUTPUT -

rateCardId=BALS_NR

adjustments|rate1=-0.2

miPricingVO=null

adjustments|adjustmentType=LOAN_AMOUNT_GREATER_THAN_550K

adjustments|adjustmentType1=AMORTIZATION_TERM_LESS_THAN_30_YEARS

adjustments|rate=0.75

optimumPricing=false

totalInitialRate=1.95

rateName=My Special Rate

ratingInfoBaseRate=1.

like image 36
Shubham Pandey Avatar answered Feb 14 '23 08:02

Shubham Pandey