READ JSON String in servlet

前端 未结 4 1715
我在风中等你
我在风中等你 2020-11-29 04:21

I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String. Its getting posted successfully but on the Servlet side I need to read these key-val

4条回答
  •  情书的邮戳
    2020-11-29 04:31

    So here goes my example. I used json.JSONTokener to tokenize my String. ( Json-Java API from here https://github.com/douglascrockford/JSON-java )

    String sJsonString = "{\"name\":\"abc\",\"age\":\"21\"}";
    // Using JSONTokener to tokenize the String. This will create json Object or json Array 
    // depending on the type cast.
    json.JSONObject jsonObject = (json.JSONObject) new json.JSONTokener(sJsonString).nextValue();
    
    Iterator iterKey = jsonObject.keys(); // create the iterator for the json object.
    while(iterKey.hasNext()) {
        String jsonKey = (String)iterKey.next(); //retrieve every key ex: name, age
        String jsonValue = jsonObject.getString(jsonKey); //use key to retrieve value from 
    
        //This is a json object and will display the key value pair.
    
        System.out.println(jsonKey  + " --> " + jsonValue  );
    }
    

    Output:
    age-->21
    name-->abc

提交回复
热议问题