How to fetch a parameter value from parsed String (Json Request)

Viewed 38

I have json request which I have parsed as a String and I need to fetch a param value of "sitename" that is "SIT-SITE-2219" from the long json request using Java.Please help .

"siteCounty":"UC",
         "alocCounty":"test2",
         "alocLat":"39.98",
         "siteName":"SIT-SITE-2219",
         "requestedBy":"UnitTester",
         "msc":"test",
2 Answers

Use gson YourClass yourClass = new Gson().fromJson("siteCounty":"UC", "alocCounty":"test2", "alocLat":"39.98", "siteName":"SIT-SITE-2219", "requestedBy":"UnitTester", "msc":"test", YourClass.class);

yourClass.getSiteName();

You can use untyped map to read the json, and then do a kv lookup. Something like the following:

        String jsonString = "{\"siteCounty\":\"UC\",\n" +
                "         \"alocCounty\":\"test2\",\n" +
                "         \"alocLat\":\"39.98\",\n" +
                "         \"siteName\":\"SIT-SITE-2219\",\n" +
                "         \"requestedBy\":\"UnitTester\",\n" +
                "         \"msc\":\"test\"}";

        ObjectMapper mapper = new ObjectMapper();

        TypeReference<HashMap<String, String>> typeRef
                = new TypeReference<HashMap<String, String>>() {};
        Map<String, String> map = null;
        try {
           map =  mapper.readValue(jsonString, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map.get("siteName"));

Example uses the following dependencies on Java:8

   compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.11.0'
   compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
Related