本地json文件解析的实践

场景:

调用外部接口取数据时,poatman可以正常使用,本地调用乱码;

数据量不是很大;

解决:

用postman调用外部接口取出数据存在本工程json文件下,代码取数据的时候直接从本地取:

本地json文件解析的实践_第1张图片

文件目录格式:

其中test.json存放数据;

JSONReadTest.java中实现逻辑操作:

代码实现:

package com.example.selectBin;

import com.alibaba.fastjson.JSONObject;
import com.example.SelectBinApplication;
import com.google.common.base.Charsets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.WebApplicationContext;

import java.io.File;
import java.io.FileInputStream;

@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SelectBinApplication.class)
public class JSONReadTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

//    protected Logger logger = Logger.getLogger(this.getClass());

    @Before
    public void setMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testWorkGroup() throws Exception{

        String  originalMsg = this.getJson("mock/test.json").toJSONString();
        //业务逻辑操作
        //....
        System.out.println("msg===msg=>"+originalMsg);

    }

    public static JSONObject getJson(String json) throws Exception {
        return JSONObject.parseObject(getResourceStr(json));
    }

    private static String getResourceStr(String path) throws Exception {
        File file = ResourceUtils.getFile("classpath:" + path);
        byte[] buffer = new byte[(int)file.length()];
        FileInputStream is = new FileInputStream(file);
        is.read(buffer, 0, buffer.length);
        is.close();
        String jsonStr = new String(buffer, Charsets.UTF_8);
        return jsonStr;
    }

}

这里用到的一些jar包不在罗列,我本工程用的maven管理的

效果:

2019-05-18 10:13:05.680  INFO 2260 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 33 ms
msg===msg=>{"xx":"xx"}
2019-05-18 10:13:05.909  INFO 2260 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
Disconnected from the target VM, address: '127.0.0.1:49784', transport: 'socket'

Process finished with exit code 0

 

你可能感兴趣的:(Java)