0

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?

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 + "]";
        }



    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.