Export objects into json files
Preface
Requirement: Export complex objects to a json file, then import the json file to generate corresponding data.
Used for data migration in different environments, this article mainly records the first half (exporting objects as json files)
1. One controller solves the problem
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value = "json/file")
public class JsonFileController {
@GetMapping(value = "download")
public void downLoad(HttpServletResponse response) {
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;fileName=demo.json");
// 制造假数据,模拟JSON数据
List<Person> list = new ArrayList<>();
list.add(new Person(1L, "张三", 18));
list.add(new Person(2L, "李四", 20));
list.add(new Person(3L, "王五", 26));
ByteArrayInputStream is = null;
OutputStream os = null;
try {
// 对象转换为字符串
// String s = JSON.toJSONString(list);
String s = "{\"code\":0,\"data\":\"aaaaaa\",\"msg\":\"成功\"}";
System.out.println(s);
is = new ByteArrayInputStream(s.getBytes());
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2. Export file name
For details, see: fileName=demo.json
response.setHeader("Content-Disposition", "attachment;fileName=demo.json");
Summarize
In postman, you will get the json file content directly
When on the browser, you will get a file directly