Featured image of post Json使用

Json使用

Json使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Json {

    private static final String demoDtoStr = "{\"stationNos\":[\"FL-HDZ001\",\"FL-HDZ002\"],\"override\":true,\"reportWeek\":21}";
    private static final String stationNosStr = "[\"FL-HDZ001\",\"FL-HDZ002\"]";

    // 在线字符串转数组(Array)  http://www.txttool.com/t/?id=NTE0
    public static void main(String[] args) throws JsonProcessingException {
        JsonDTO jsonDTO = new JsonDTO();
        jsonDTO.setStationNos(List.of("FL-HDZ001", "FL-HDZ002"));
        jsonDTO.setOverride(true);
        jsonDTO.setReportWeek(21);

        // Java对象 转 json字符串
        String string = new ObjectMapper().writeValueAsString(jsonDTO);
        // Java对象 转 具体Java类 注意类需要构造器,否者报错
        JsonDTO jsonDTO2 = new ObjectMapper().convertValue(jsonDTO, JsonDTO.class);
        // Java对象 转 Map,先转string再转map
        Map<String, Object> map = new ObjectMapper().readValue(demoDtoStr, new TypeReference<>() {
        });
        
        // json字符串 转 Java对象
        JsonDTO jsonDTO1 = new ObjectMapper().readValue(demoDtoStr, JsonDTO.class);
        // json字符串 转 List
        List<String> strings = new ObjectMapper().readValue(stationNosStr, new TypeReference<>() {
        });
    }

    @Data
    public static class JsonDTO {
        private List<String> stationNos;
        private Boolean override = false;
        private Integer reportWeek;
    }

}

JsonUtil工具类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class JsonUtil {
    private static final ObjectMapper objectMapper;

    static {
        objectMapper = Jackson2ObjectMapperBuilder
                .json()
                .failOnEmptyBeans(false) // 拆开循环依赖
                .serializerByType(Long.TYPE, ToStringSerializer.instance) // Long类型转String
                .serializerByType(Long.class, ToStringSerializer.instance) // Long类型转String
                .featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // 时间戳格式
                .featuresToEnable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS) // 时间戳格式
                .serializationInclusion(JsonInclude.Include.NON_NULL) // 忽略null字段
                .failOnUnknownProperties(false) // 忽略未知字段
                .build();
    }
}

Spring Boot解析Json文件-本地解析-Web上传解析

本地json文件解析

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import com.fasterxml.jackson.databind.ObjectMapper;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
import java.io.IOException;  
import java.util.List;  
  
@Service  
public class JsonFileService {  
  
    private final ObjectMapper objectMapper = new ObjectMapper();  
  
    public List<Person> readPersonsFromJsonFile() throws IOException {  
        Resource resource = new ClassPathResource("persons.json");  
        return objectMapper.readValue(resource.getInputStream(), new TypeReference<List<Person>>() {});  
    }  
}

web文件上传解析

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

  private final ObjectMapper objectMapper = new ObjectMapper();

  @PostMapping("/json")
  public void uploadJsonFile(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "File is empty");
    }

    try {
      List<Person> persons = objectMapper.readValue(file.getInputStream(), new TypeReference<List<Person>>() {
      });
    } catch (IOException e) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "json文件解析失败");
    }
  }
}

教程涉及的文件和Java类

persons.json文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[  
  {  
    "id": 1,  
    "name": "John Doe",  
    "age": 30  
  },  
  {  
    "id": 2,  
    "name": "Jane Doe",  
    "age": 25  
  }  
]

Java类

1
2
3
4
5
6
7
public class Person {  
    private int id;  
    private String name;  
    private int age;  
  
    // 构造函数、getter和setter省略  
}
皖ICP备2024056275号-1
发表了78篇文章 · 总计148.99k字
本站已稳定运行