Maven依赖
Fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
commons-io
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Json文件内容
{
"name":"网站",
"num":3,
"sites":[ "Google", "Runoob", "Taobao" ]
}
代码示例
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
//类路径资源
ClassPathResource classPathResource = new ClassPathResource("test.json");
//获取file对象
File file = classPathResource.getFile();
//将file对象转为字符串
String s = FileUtils.readFileToString(file);
//将字符串解析为JSONObject对象
JSONObject jsonObject = JSONObject.parseObject(s);
//获取数组对象
JSONArray sites = jsonObject.getJSONArray("sites");
//遍历数组对象
sites.forEach(x -> {
System.out.println(x.toString());
});
//将json转为对象
t t = JSONObject.parseObject(s, t.class);
System.out.println(t);
}
}
@Data
class t{
String name;
Integer age;
String[] sites;
}
网友评论