Question

I have a Java class in a servlet that uses GSON to render posted JSON Strings into a Java object. The beauty of the approach is, that GSON filters out all JSON elements that don't match a class property, so I never end up with JSON content that I don't want to process. The servlet's doPost (simplified) looks like this:

  protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;
    try {
        InputStream in = request.getInputStream();
        Demo d = Demo.load(in);
        in.close();
        response.setContentType("text/plain");
        response.setStatus(HttpServletResponse.SC_OK);
        out = response.getWriter();
        out.println(d.toJson);
    } catch (Exception e) {
        e.printStackTrace();
        out.println(e.getMessage());
    }
    out.close();
}

The Demo class (and that's the one I need to recreate in common.js or node.js looks like this:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Demo implements Serializable {

    public static Demo load(InputStream in) {
        Demo result = null;
        try {
            Gson gson = new GsonBuilder().create();
            result = gson.fromJson(new InputStreamReader(in), Demo.class);
        } catch (Exception e) {
           result = null;
        }   
        return result;
    }

    @TypeDiscriminator
    @JsonProperty("_id")
    private String              id                  = UUID.randomUUID().toString();
    private Date                created             = new Date();
    private String              color;
    private String              name;
    private String              taste;

    public String getColor() {
        return this.color;
    }

    public String getName() {
        return this.name;
    }

    public String getTaste() {
        return this.taste;
    }

    public Date getCreated() {
        return this.created;
    }

    public String getId() {
        return this.id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setTaste(String taste) {
        this.taste = taste;
    }


    public void setColor(String color) {
        this.color = color;
    }

    public String toJson() {
        GsonBuilder gb = new GsonBuilder();
        gb.setPrettyPrinting();
        gb.disableHtmlEscaping();
        Gson gson = gb.create();
        return gson.toJson(this);
    }
}

Obviously I stripped out all the processing logic and the servlet just echos the JSON back, which is not what the app does, but serves to illustrate the point. I can throw pretty any String in a HTTP Post at that example and I only get valid Demo objects.

How would I do something like this in node.js?

Was it helpful?

Solution

Node.js is Javascript so has built in support for json. You can use JSON.parse to convert from string to json and wrap in try catch block.

To only include select properties there is no built in feature in node that I know of unless you are using Mongodb with mongoose, but you could do following: Have a "class" that is an object containing all properties that you want and delete those from parsed json object that are not in that "class" object.

var class = {x: null, y:null};
for(var prop in object){ 
if (!class.hasOwnProperty (prop)) {
delete object [prop]
}

It would be best to use this class as object and expose parseJSON function to encapsulate this functionality

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top