Anmol Singh Jaggi Anmol Singh Jaggi - 1 year ago 164
Java Question

Parse json array of different object types

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 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;

public class serv1 extends HttpServlet {
private static final long serialVersionUID = 1L;

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

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

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

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


* @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
is correctly outputting the first object of the array, I am not able to figure out how to access the properties of the object:


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.

Answer Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download