如何转换json?

x4shl7ld  于 2021-07-15  发布在  Java
关注(0)|答案(3)|浏览(260)

我想把firstname和lastname转换成json格式。

@RestController
public class studentsController {

    @GetMapping(value = "/students", produces = { MediaType.APPLICATION_JSON_VALUE } )
    @ResponseBody
    public String getWhoami(@RequestParam String firstname, @RequestParam String lastname ) {
        return "firstname:" + firstname + " lastname: " + lastname;
    }
}

我怎样才能像这些格式转换;

{"firstname": "value1", "lastname": "value2"}

我试着去看Jackson,但做不到。

jm81lzqq

jm81lzqq1#

您不必手动创建json。创建一个类,如:

class Student {
    private String firstname;
    private String lastname;

    public Student(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname  =lastname;
    }
    // getters and setter 
}
@GetMapping(value = "/students", produces = { MediaType.APPLICATION_JSON_VALUE } )
    @ResponseBody
    public Student getWhoami(@RequestParam String firstname, @RequestParam String lastname ) {
        return new Student(firstname, lastname);
    }

对象将自动转换为json。

qmb5sa22

qmb5sa222#

你试过这样的Jackson吗?
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
在类中添加如下示例:

ObjectMapper mapper = new ObjectMapper();
private ObjectMapper mapper = new ObjectMapper();

从示例中尝试如下函数:

String jsonstr = mapper.writeValueAsString(object);

假设您的项目中已经有jackson库(jar文件)
下面是示例类:

public class SampleClass{
      private ObjectMapper mapper = new ObjectMapper();

      public String sampleMethodToJSONString(Student student){
          return mapper.writeValueAsString(student);
      }

}
vd8tlhqk

vd8tlhqk3#

您可以将返回数据类型更改为使用map<string,string>而不是string,或者使用responsebody<?>

相关问题