将json从文件转换为java对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18638229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting json from a file to a java object
提问by Hyman
I am trying to convert json from a text file into a java object.
我正在尝试将 json 从文本文件转换为 java 对象。
I have tried both the Hymanson library, I put in the dependency and what not. My json file has both camel case and underscores, and that is causing an error when running my program. Here is the code that I used for when relating to the gson librar and it does not do anything, the output is the same with or without the code that I placed.
我已经尝试了 Hymanson 库,我放入了依赖项,什么没有。我的 json 文件有驼峰式大小写和下划线,这在运行我的程序时导致错误。这是我在与 gson 库相关时使用的代码,它不执行任何操作,无论是否包含我放置的代码,输出都相同。
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
try
{
BufferedReader br = new BufferedReader(new FileReader("/test.json"));
// convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e)
{
e.printStackTrace();
}
Now I also tried the Hymanson library. Here is the code i used
现在我也尝试了 Hymanson 库。这是我使用的代码
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
InputStream is = Test_Project.class.getResourceAsStream("/test.json");
SampleDto testObj = mapper.readValue(is, SampleDto.class);
System.out.println(testObj.getCreatedByUrl());
I am not sure what to do,
我不知道该怎么做,
采纳答案by Ilya
This simple example works like a charm:
DTOs
这个简单的例子很有魅力:
DTOs
public class SampleDTO
{
private String name;
private InnerDTO inner;
// getters/setters
}
public class InnerDTO
{
private int number;
private String str;
// getters/setters
}
Gson
格森
BufferedReader br = new BufferedReader(new FileReader("/tmp/test.json"));
SampleDTO sample = new Gson().fromJson(br, SampleDTO.class);
Hymanson
Hyman逊
InputStream inJson = SampleDTO.class.getResourceAsStream("/test.json");
SampleDTO sample = new ObjectMapper().readValue(inJson, SampleDTO.class);
JSON(test.json
)
JSON( test.json
)
{
"name" : "Mike",
"inner": {
"number" : 5,
"str" : "Simple!"
}
}
回答by Vinit Jordan
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
/**
* Read object from file
*/
Person person = mapper.readValue(new File("/home/document/person.json"), Person.class);
System.out.println(person);
}