سؤال

My sample JSON input is as follows:

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

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

Currently, I'm 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 do I search for the field "InputHiveTable" while ignoring the case. I'm using JSON Simple libraries.

هل كانت مفيدة؟

المحلول

If you have to perform this case-insensitive lookup many times, I'd just write a method to do that lookup:

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;

}

نصائح أخرى

Given that case-insensitivity can be achieved with TreeMap (i.e. via String.CASE_INSENSITIVE_ORDER comparator), you can probably do the following:

  1. Implement your own MyJSONObject extending TreeMap where its methods will be just calling static methods of JSONObject with the same signatures and all required interfaces as in JSONObject. In default constructor write super(String.CASE_INSENSITIVE_ORDER)

  2. Implement ContainerFactory interface where createObjectContainer will return new instance of MyJSONObject (and createArrayContainer will just return new JSONArray).

  3. To run it with new container MyContainerFactory:

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

You could read the JSONObject into a java string, and call String.toLowerCase on it and store it back into a JSONObject. This will turn the entire case of the string to lower case, so you will have to account for that elsewhere in your logic. After that, you then would just have to do a get call on "inputhivetable".

By no means is it a pretty solution, but it is a potential work around if there is absolutely no other way for you to handle what you're returning as your JSON input.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top