How to ignore case when searching for JSON object

My example JSON input looks like this:

"JobName":"Test Job 1", "events":[ { "features":[], "InputHiveTable":"uilog_uiclientlogdata", "eventColumn":"command", "name":"edu.apollogrp.classroom.discussion.client.events.CreateDiscussionEvent" }, 

Consider the field "InputHiveTable" , it can be in all uppercase letters INPUTHIVETABLE , all lowercase letters INPUTHIVETABLE or a mixture of both, as it is now.

I am currently reading the field as follows (in Java):

 JSONObject jsonObject = (JSONObject) obj; JSONArray events = (JSONArray) jsonObject.get("events"); String InputHiveTable = (String)event.get("InputHiveTable"); 

So my question is how to look for the "InputHiveTable" field while ignoring this case. I am using JSON Simple libraries.

+6
source share
4 answers

If you need to perform this case-insensitive analysis many times, I would simply write a method for this search:

 public Object getIgnoreCase(JSONObject jobj, String key) { Iterator<String> iter = jobj.keySet().iterator(); while (iter.hasNext()) { String key1 = iter.next(); if (key1.equalsIgnoreCase(key)) { return jobj.get(key1); } } return null; } 
+14
source

A JSONObject is implemented as a Hashmap

 public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{ 

Thus, there is no way to ignore the case of the String key when trying to get the displayed value. You will have to come up with some rules to create this JSON.

+1
source

Given that TreeMap (i.e. using String.CASE_INSENSITIVE_ORDER comparator) can be case insensitive), you can do the following:

  • Implement your own MyJSONObject extending TreeMap , where its methods will simply call the static JSONObject methods with the same signatures and all the necessary interfaces as in JSONObject . In the default constructor, write super(String.CASE_INSENSITIVE_ORDER)

  • Deploy the ContainerFactory interface where createObjectContainer will return a new instance of MyJSONObject (and createArrayContainer will just return a new JSONArray ).

  • To start it with the new MyContainerFactory container:

      StringReader in = new StringReader(yourJSONString); JSONParser parser = new JSONParser(); parser.parse(in, yourContainerFactory) 
+1
source

You can read JSONObject in a java string and call String.toLowerCase on it and save it back to JSONObject. This will turn the entire case of the string to lowercase, so you will have to consider this elsewhere in your logic. After that, you just need to call "inputhivetable".

This is by no means a pretty acceptable solution, but it is potential work if there is absolutely no other way to handle what you return as JSON input.

0
source

Source: https://habr.com/ru/post/951061/


All Articles