简体   繁体   中英

Convert JSON String to JSON object to get Values

I am getting a JSON string and want to print Name values on the console via JSP. Can someone suggest how to do it?

String AllCustomLockingCriterias = '{"TemplateArray":[{"Id":16,"Name":"Machine","type":"PM"},
                                      {"Id":17,"Name":"Ethernet","type":"PM"},
                                      {"Id":18,"Name":"Hard Disk","type":"PM"}]}';

Output I need:

Machine
Ethernet
Hard Disc

I want to start a loop and my output will be:

Machine
Ethernet
Hard Disc
  1. use Gson jar package(produced by google.com) , FastJson(produced by alibaba.com) or jackson to serialize or deserialize the json string and the Class object.One jar package is enough.
  2. use maven pom dependency/gradle config to add the gson to your project or add the gson jar into your lib folder directly,it is all up to you, maven is preferred.
  3. define the Java Class field member,with the meta info from your json string,such as 'id','name','type'.The Java Class can be named 'Template'(do not forget to implement the java Serializable interface).
  4. code example:
 Gson gson = new Gson(); TypeToken typeToken = new TypeToken<List<Template>>() {}; Type type = typeToken.getType(); List<Template> templates = gson.fromJson(json, type);
  1. return the templates list to the front jsp page within the jsp page scope. if you user springMVC framework,you can add a model param to the method params,
 @RequestMapping(value = "/test",method = RequestMethod.GET) public String test(Model model){ model.addAttribute("templates",templates); return "jspFileName"; }
  1. for jsp site,you can use jsp EL Express to show the list
<c:forEach items="${templates}" var = "template"> ${template.name} </c:forEach>
  1. the last but the most easy method is ,you can pass the json string to the jsp page.on the other words,do not need to serialize the json string to class,just pass the string to the jsp with the model attribute provided by springMVC or even the basic Servlet.And then use the javascript method to handle the json string.for example,
 var obj = JSON.parse(json); var array = obj.TemplateArray; array.foreach(function(item) { console.log(item.name); });

Use JsonNode with JPointer .

Example:

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(
                    "{\"TemplateArray\":[{\"Id\":16,\"Name\":\"Machine\",\"type\":\"PM\"}, {\"Id\":17,\"Name\":\"Ethernet\",\"type\":\"PM\"},{\"Id\":18,\"Name\":\"Hard Disk\",\"type\":\"PM\"}]}",
                    JsonNode.class);

node.at("/TemplateArray").forEach(a -> System.out.println(a.at("/Name")));

Prints:

"Machine"
"Ethernet"
"Hard Disk"

"fasterxml" or "jackson" has Java library that is able to transform your JSON string to a TreeNode. You can then access various fields.

@Test
public void test() throws IOException {
    String AllCustomLockingCriterias = "{\"TemplateArray\":[{\"Id\":16,\"Name\":\"Machine\",\"type\":\"PM\"},\n" +
            "                   {\"Id\":17,\"Name\":\"Ethernet\",\"type\":\"PM\"},\n" +
            "                  {\"Id\":18,\"Name\":\"Hard Disk\",\"type\":\"PM\"}]}";


    //create mapper to map JSON string to handy Java object
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readValue(AllCustomLockingCriterias,JsonNode.class);

    //fetch value that has field name "TemplateArray"
    JsonNode templateArray = rootNode.get("TemplateArray");

    //loop over the values in the TemplateArray and extract Name, if present.
    for(JsonNode subNode : templateArray){
        if(subNode.has("Name")){
            System.out.println(subNode.get("Name"));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM