Mike
Mike

Reputation: 919

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());;
        }

Upvotes: 4

Views: 17303

Answers (4)

Ralph
Ralph

Reputation: 4868

You can use the standard JsonParser which is part of the javax.json package. This parser is part of Java EE since version 7 and you can use this parser without any additional library.

The parser allows you to navigate through a JSON structure using the so called 'pull parsing programming model'

 JsonParser parser = Json.createParser(myJSON);
 Event event = parser.next(); // START_OBJECT
 event  = parser.next(); // KEY_NAME
 String key = parser.getString(); // 'rateName'
 event = parser.next(); // STRING_VALUE
 String value=parser.getString(); // 'My Special Rate'
 event  = parser.next(); // START_ARRAY
 ....

But of course you need to navigate through your json data structure

Upvotes: 0

Shubham Pandey
Shubham Pandey

Reputation: 29

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.

Upvotes: 2

igr
igr

Reputation: 10604

Or you can just use Jodd JSON parser. You just need to deserialize the input string and the result will be collected in regular Map and List.

JsonParser jsonParser = new JsonParser();
Map<String, Object> map = jsonParser.parse(input);

Simple as that - and the result is the most generic as it can be. Then just call map.get("rateName") to get your value and so on.

But notice that for adjustments you can get the way you want without some util method that would iterate elements and search for the right one. If you can, change the JSON so that you dont have an array of adjustments, but a map.

If you need specific results, just pass the type with the input string. See more about parsing features.

Upvotes: -1

meda
meda

Reputation: 45490

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");
}

Upvotes: 7

Related Questions