How to parse JSON file?

后端 未结 3 874
礼貌的吻别
礼貌的吻别 2020-12-09 05:49

Simple situation -

  1. read a json file
  2. discover all key-value pairs
  3. compare key-value pairs

I tried gson, package from json.org,

相关标签:
3条回答
  • 2020-12-09 06:30

    With Gson (assuming that you have on object {...} on the top level of your json file):

    final JsonParser parser = new JsonParser();
    final JsonElement jsonElement = parser.parse(new FileReader("/path/to/myfile"));
    final JsonObject jsonObject = jsonElement.getAsJsonObject();
    
    for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
       final String key = entry.getKey();
       final JsonElement value = entry.getValue();
       ....
    }
    

    In response to your comment:

    You should certainly avoid re-parsing the json from a string. Use something like:

    ... else if (value.isJsonArray()) {
       final JsonArray jsonArray = value.getAsJsonArray();
       if (jsonArray.size() == 1) {
          runThroughJson(jsonArray.get(0));
       } else {
            // perform some error handling, since
            // you expect it to have just one child!
       }
    
    } 
    
    0 讨论(0)
  • 2020-12-09 06:36

    We use Jaskson parser, here are the sample code:

    protected T getJsonObject(InputStream inputStream, Class<T> className) throws JsonParseException,
          JsonMappingException, IOException {
        // Deserialize input to Json object
        ObjectMapper mapper = new ObjectMapper();
    
        T jsonSource = mapper.readValue(inputStream, className);
        return jsonSource;
    }
    

    Here is the code how to invoke it:

    JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);
    

    JsonEmployee.java is just POJO

    0 讨论(0)
  • 2020-12-09 06:49

    XStream is good for JSON: http://x-stream.github.io/json-tutorial.html

    Due to XStream's flexible architecture, handling of JSON mappings is as easy as handling of XML documents. All you have to do is to initialize XStream object with an appropriate driver and you are ready to serialize your objects to (and from) JSON.

    0 讨论(0)
提交回复
热议问题