如何使用jackson在java中将输入字符串转换为json字符串或json对象

6
如何使用jackson在Java中将输入字符串转换为JSON字符串或JSON对象。
提前感谢。

你目前尝试过什么了吗?(Google或在Stack Overflow上搜索都是很容易的选择) - ceekay
1
你是在哪个上下文中谈论?你正在处理网络服务吗?请提供更多细节。 - Garry
1
public static JsonObject jsonStringToJsonObj(String jsonString) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, new TypeReference<JsonObject>() {}); } - Vivek Sinha
3个回答

7
这是在mkyong上记录的,并在此引用:
Jackson是一个高性能的JSON处理Java库。 在本教程中,我们将向您展示如何使用Jackson的数据绑定将Java对象转换为/从JSON。
对于对象/ JSON转换,您需要了解以下两种方法:
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);

注意:writeValue()和readValue()都有许多重载方法来支持不同类型的输入和输出。确保查看它们。
  1. Jackson Dependency Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion, just declares following dependency in your pom.xml

    <repositories>
        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    
    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.5</version>
        </dependency>
    </dependencies>
    

    For non-maven user, just get the Jackson library here.

  2. POJO

    An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.

    package com.mkyong.core;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class User {
    
        private int age = 29;
        private String name = "mkyong";
        private List<String> messages = new ArrayList<String>() {
            {
                add("msg 1");
                add("msg 2");
                add("msg 3");
            }
        };
    
        //getter and setter methods
    
        @Override
        public String toString() {
            return "User [age=" + age + ", name=" + name + ", " +
                    "messages=" + messages + "]";
        }
    }
    
  3. Java Object to JSON Convert an “user” object into JSON formatted string, and save it into a file “user.json“.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        User user = new User();
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // convert user object to json string, and save to a file
            mapper.writeValue(new File("c:\\user.json"), user);
    
            // display to console
            System.out.println(mapper.writeValueAsString(user));
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

    Output

    {"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
    

    Note Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

  4. JSON to Java Object

    Read JSON string from file “user.json“, and convert it back to Java object.

    package com.mkyong.core;
    
    import java.io.File;
    import java.io.IOException;
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonExample {
        public static void main(String[] args) {
    
        ObjectMapper mapper = new ObjectMapper();
    
        try {
    
            // read from file, convert it to user class
            User user = mapper.readValue(new File("c:\\user.json"), User.class);
    
            // display to console
            System.out.println(user);
    
        } catch (JsonGenerationException e) {
    
            e.printStackTrace();
    
        } catch (JsonMappingException e) {
    
            e.printStackTrace();
    
        } catch (IOException e) {
    
            e.printStackTrace();
    
        }
    
      }
    
    }
    

输出

    User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]

0
在Java中,我们可以使用许多方法将字符串转换为JSON。您可以使用集合HashMap来实现此目的,它会以{键:值}对的形式提供值,这可能对您有用,如果您正在使用Spring,则这可能对您有帮助。
   //****************** update The user Info**********************//
        @RequestMapping(value = "/update/{id}",  method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody
        Status updateMsBuddy(@RequestBody MsBuddyInfo msBuddyInfo){

            try{
                if(msBuddyService.updateMsBuddy(msBuddyInfo))
                return new Status(1, "MsBuddyInfo updated Successfully",+msBuddyInfo.getId());
                else
                    return new Status(1, "unable to updated Profile",+msBuddyInfo.getId());
            }
            catch(Exception e){

                return new Status(0,e.toString());
            }
        }

0

来自journaldev的非常好的教程 Jackson-JSON处理

您可以使用jackson API的com.fasterxml.jackson.databind.ObjectMapper类来读取或编写格式化为字符串的json对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接