Domanda

Is their an easy way or library to convert a JSON String to a Java object such that I can easily reference the elements in a JSP page? I think Map's can be referenced with simple dot notation in JSP pages, so JSON -> Map object should work?

UPDATE: Thank you for all the JSON Java libraries. In particular, I'm looking for a library that makes it easy for consumption in JSP pages. That means either the Java object created has appropriate getter methods corresponding to names of JSON nodes (is this possible?) or there's some other mechanism which makes it easy like the Map object.

È stato utile?

Soluzione

Use Jackson.

Updated:

If you have an arbitrary json string Jackson can return a map object to access the properties values.

Here a simple example.

@Test
public void testJsonMap() throws JsonParseException, JsonMappingException, IOException {
    String json = "{\"number\":\"8119123912\",\"msg\":\"Hello world\"}";
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
    System.out.println("number:" + map.get("number") + " msg:" + map.get("msg"));
}

Output:

number:8119123912 msg:Hello world

Altri suggerimenti

Try GSON, here is a tutorial.

This library should do what you want: http://www.json.org/java/

DWR can be used for this purpose DWR - Easy Ajax for JAVA .

Lets consider this java class.

   class Employee
   {
      int id;
      String eName;
       // setters and getters                
   }   

In javascript JSON object

   var employee = {
                   id   : null,
                   name : null
                  };

This is the call to java method from javascript function.

   EmployeeUtil.getRow(employee,dwrData);

In getRow() of EmployeeUtil class, return type of method will be Employee.

   Employee getRow();

So using the setters of Employee set the data.

dwrData is the callback function.

   function dwrData(data) {
                            employee=data;                   
                          }

The data returned which is Employee bean will be in callback function.

Just initialize this in javascript JSON object.

Now the JSON object can be parsed and displayed in jsp.

This example shows Dynamically Editing a Table

Hope this helps ....

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top