Kimi
Kimi

Reputation: 6289

Parsing JSON from request parameters in a HttpServlet

I need to implement a parser which parses some values from "JSON strings". The data is accessible from the request parameters as follows:

String[] criterion = request.getParameterValues("criteria");

The criterion contains the following strings (each row represents a String):

{"fieldName":"name","operator":"iContains","value":"a string"}
{"fieldName":"date","operator":"equals","value":"2013-02-26"}
{"fieldName":"amount","operator":"equals","value":2600}

I need to be able to get the values from criterion by fieldName. The API could be like this:

String name = CoolParserUtil.parseParam(criterion, "name", String.class);
// "a string"
Date date = CoolParserUtil.parseParam(criterion, "date", Date.class);
// date representing 2013-02-26
// etc. etc.

How would you implement the parser?

Upvotes: 0

Views: 1724

Answers (2)

Sudhakar
Sudhakar

Reputation: 4873

Well you can easily parse the String to a Object in Java using any of innumerable Json libs available. My fav would be google-gson

Heres how you do it with google json

import com.google.gson.Gson;
public class GsonTutorial {

    public static void main(String[] args) {

String jsonMsg ="{\"fieldName\":\"name\",\"operator\":\"iContains\",\"value\":\"a string\"}";

        Gson gson = new Gson();
        Data data = (Data) gson.fromJson(jsonMsg, Data.class);

        System.out.println(data);
    }

    class Data{
        private String fieldName;
        private String operator;
        private String value;
        public String getFieldName() {
            return fieldName;
        }
        public void setFieldName(String fieldName) {
            this.fieldName = fieldName;
        }
        public String getOperator() {
            return operator;
        }
        public void setOperator(String operator) {
            this.operator = operator;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
        public String toString() {
            return "Data [fieldName=" + fieldName + ", operator=" + operator
                    + ", value=" + value + "]";
        }



    }

}

Upvotes: 1

user2030471
user2030471

Reputation:

You should have a look at JSON in Java.

There is another one named google-gson which offers features like defining type-adapters for serialization and deserialization for custom types. You can find a use-case here.

Upvotes: 2

Related Questions