有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    如果您知道Jackson 2,那么mkyong.com上有一个关于如何将Java对象转换为JSON以及如何将Java对象转换为JSON的精彩教程。以下代码片段取自该教程

    将Java对象转换为JSON,writeValue(...):

    ObjectMapper mapper = new ObjectMapper();
    Staff obj = new Staff();
    
    //Object to JSON in file
    mapper.writeValue(new File("c:\\file.json"), obj);
    
    //Object to JSON in String
    String jsonInString = mapper.writeValueAsString(obj);
    

    将JSON转换为Java对象,readValue(...):

    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = "{'name' : 'mkyong'}";
    
    //JSON from file to Object
    Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
    
    //JSON from URL to Object
    Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
    
    //JSON from String to Object
    Staff obj = mapper.readValue(jsonInString, Staff.class);
    

    Jackson 2依赖项:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
    </dependency>
    

    有关完整教程,请转到上面给出的链接

  2. # 2 楼答案

    看看https://www.json.org

    假设您有这样一个简单的Java类:

    public class Person {
    
        private String name;
        private Integer age;
    
        public String getName() { return this.name; }
        public void setName( String name ) { this.name = name; }
    
        public Integer getAge() { return this.age; }
        public void setAge( Integer age ) { this.age = age; }
    
    }
    

    因此,将其转换为JSON对象非常简单。像这样:

    import org.json.JSONObject;
    
    public class JsonTest {
    
        public static void main( String[] args ) {
            Person person = new Person();
            person.setName( "Person Name" );
            person.setAge( 333 );
            
            JSONObject jsonObj = new JSONObject( person );
            System.out.println( jsonObj );
        }
    
    }
    

    这里有另一个例子,在本例中使用Jackson:https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/

    马文:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.1</version>
    </dependency>
    

    以及查找最新/最佳版本的链接(如下所示):

    https://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22com.fasterxml.jackson.core%22%20AND%20a%3A%22jackson-databind%22

  3. # 3 楼答案

    您可以使用jackson api进行转换

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
    </dependency>
    

    在POM的主方法CreateObjectMapper中添加上述maven依赖项

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    

    稍后,我们需要将POJO类添加到映射器中

    String json = mapper.writeValueAsString(pojo);
    
  4. # 4 楼答案

    使用GSON将POJO转换为JSONObjectRefer here.

    要将JSONObject转换为POJO,只需在POJO中调用setter方法,并直接从JSONObject分配值

  5. # 5 楼答案

    我们还可以在pom文件中使用下面给定的依赖项和插件——我使用maven。通过使用这些,您可以根据JSON模式生成POJO,然后使用下面给出的代码通过指定为gson参数的src对象填充请求JSON对象。toJson(对象src)或反之亦然。请看下面的代码:

    Gson gson = new GsonBuilder().create();
    String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());
    
    Gson gson2 = new Gson();
    Error expectederr = gson2.fromJson(payloadStr, Error.class);
    

    以及Maven设置:

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>1.7.1</version>
    </dependency>
    
    <plugin>
        <groupId>com.googlecode.jsonschema2pojo</groupId>
        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
        <version>0.3.7</version>
        <configuration>
            <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
            <targetPackage>com.example.types</targetPackage>
        </configuration>
        <executions>
            <execution>
                <phase>generate-sources</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    
  6. # 6 楼答案

    使用下面的引用将JSON转换为POJO,反之亦然

    假设您的JSON模式如下所示:

    {
      "type":"object",
      "properties": {
        "dataOne": {
          "type": "string"
        },
        "dataTwo": {
          "type": "integer"
        },
        "dataThree": {
          "type": "boolean"
        }
      }
    }
    

    然后,要转换为POJO,您需要按照下面的风格解释一些类:

    ==================================
    package ;
    public class DataOne
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class DataTwo
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class DataThree
    {
        private String type;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
    }
    
    ==================================
    package ;
    public class Properties
    {
        private DataOne dataOne;
    
        private DataTwo dataTwo;
    
        private DataThree dataThree;
    
        public void setDataOne(DataOne dataOne){
            this.dataOne = dataOne;
        }
        public DataOne getDataOne(){
            return this.dataOne;
        }
        public void setDataTwo(DataTwo dataTwo){
            this.dataTwo = dataTwo;
        }
        public DataTwo getDataTwo(){
            return this.dataTwo;
        }
        public void setDataThree(DataThree dataThree){
            this.dataThree = dataThree;
        }
        public DataThree getDataThree(){
            return this.dataThree;
        }
    }
    
    ==================================
    package ;
    public class Root
    {
        private String type;
    
        private Properties properties;
    
        public void setType(String type){
            this.type = type;
        }
        public String getType(){
            return this.type;
        }
        public void setProperties(Properties properties){
            this.properties = properties;
        }
        public Properties getProperties(){
            return this.properties;
        }
    }