0

I am trying to send an array of different types from Javascript to a Java servlet.

The Javascript code used to generate and send the data is:

function sendDataOnButtonPress()
{
  var obj1 = {'key_11': "val_11", 'key_12': "val_12"};
  var obj2 = {'key_21': "val_21", 'key_22': "val_22"};
  var myArray = [obj1, obj2];

  var params = {
      data: JSON.stringify(myArray)
  };

  $.post("serv1", $.param(params), function(response) {
    console.log("response = " + response);
  });
}

The Java code used to process this data is:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/serv1")
public class serv1 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    public serv1() {
        super();
        // TODO Auto-generated constructor stub
    }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String data = request.getParameter("data");
    //System.out.println(data);

    ObjectMapper mapper = new ObjectMapper();
    Object[] objs = mapper.readValue(data, Object[].class);
    System.out.println(objs[0]);

    PrintWriter writer1 = response.getWriter();
    String htmlRespone = "Dummy response";
    writer1.println(htmlRespone);

  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

Although the line System.out.println(objs[0]); is correctly outputting the first object of the array, I am not able to figure out how to access the properties of the object:

System.out.println(objs[0]["key_11"]);

is not able to compile.

So, my question is how to correctly parse the data sent from javascript inside Java?

I am open to using any json parsing library other than Jackson too.

4 Answers 4

1

You can get it as follows. The super class Object does not have a way to get the value as you indicated , hence the compiler error.

To understand which is the specific type , i printed the object's class. In this case it is a LinkedHashMap. I hence safely casted obj[0] into that. Once i have a map , i can always get a value looking up a key. Hope this helps

String data = "[{\"key_11\": \"val_11\", \"key_12\": \"val_12\"}, {\"key_21\": \"val_21\", \"key_22\": \"val_22\"}]";
ObjectMapper mapper = new ObjectMapper();
Object[] objs = mapper.readValue(data, Object[].class);
System.out.println(objs[0].getClass().getName());

LinkedHashMap<String, Object> keyValues = (LinkedHashMap) objs[0];

System.out.println(keyValues.get("key_11"));
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this with jsonNode

String json = "{ \"query\": { \"pageids\": [ \"736\" ], \"pages\": { \"736\": { \"pageid\": 736, \"ns\": 0, \"title\": \"Albert Einstein\", \"contentmodel\": \"wikitext\", \"pagelanguage\": \"en\", \"touched\": \"2014-01-05T03:14:23Z\", \"lastrevid\": 588780054, \"counter\": \"\", \"length\": 106159 } } } }";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node =mapper.readTree(json);

    node = node.get("query").get("pages");

    Map<String, Page> pages = mapper.readValue(node.traverse(), new TypeReference<Map<String, Page>>() {
    });

    System.out.println(pages.get("yourkey");

Comments

0

GSON library can also be used to parse the data (https://github.com/google/gson)

String data = request.getParameter("data");        
JsonElement jelement = new JsonParser().parse(data);       
JsonArray output =  jelement.getAsJsonArray();             
JsonElement outputElement=output.get(0);           
JsonObject iObjectOutput=outputElement.getAsJsonObject();       
String value1 = iObjectOutput.get("key_11");

Comments

0

The accepted answer's solution can be shortened to:

System.out.println(((LinkedHashMap)objs[0]).get("key_11"));

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.