[英]How to convert Json String to Java Object?
I have following json in String format. 我在String格式中跟随json。 How to convert it to a java object?
如何将其转换为java对象?
JSON Srting JSON Srting
String allCameraList = [{
"name": "Camera1",
"displayURL": "Stream-1"
}, {
"name": "Camera2",
"displayURL": "Stream-3"
}, {
"name": "Camera4",
"displayURL": "Stream-7"
}, {
"name": "Camera3",
"displayURL": "Stream-5"
}, {
"name": "Camera5",
"displayURL": "Stream-10"
}, {
"name": "Camera6",
"displayURL": "Stream-12"
}]
Java Entity class Java实体类
public class CameraDetails
{
private String name;
private String displayURL;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayURL() {
return displayURL;
}
public void setDisplayURL(String displayURL) {
this.displayURL = displayURL;
}}
When I tried to use Json parser like following: 当我尝试使用如下的Json解析器时:
JsonParser parser = new JsonParser();
String json = parser.parse(allCameraList)
.getAsJsonObject()
.getAsJsonObject("name")
.toString();
it threw the following exception: 它引发了以下异常:
java.lang.IllegalStateException: Not a JSON Object
Please note that my json string is start with [
not with {
. 请注意,我的json字符串以
[
not with {
。
You can convert a String to Json array. 您可以将String转换为Json数组。
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(allCameraList);
JSONArray json = (JSONArray) parser.parse(jsonInString);
Take a look to this also. 看看这个。
import org.codehaus.jackson.map.ObjectMapper;
static ObjectMapper mapper=new ObjectMapper();
public ObjectMapper getMapperObject(){
return mapper;
}
mapper=TypeConvertion.getMapperObject();
String jsonString=mapper.writeValueAsString(allCameraList);
List<CameraDetails> newMSExp=mapper.readValue(jsonString, new TypeReference<List<CameraDetails>>() {});
return newMSExp;
You can't really define string without using escape character '/' and double quotes to begin with. 如果不使用转义字符'/'和双引号开头,则无法真正定义字符串。 You can read it from file, convert it to string as below :
您可以从文件中读取它,将其转换为字符串,如下所示:
private static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
You can use StandardCharsets.UTF_8 as encoding method 您可以使用StandardCharsets.UTF_8作为编码方法
Next, you can do a post-processing on the string obtained. 接下来,您可以对获得的字符串进行后处理。 For your use-case the code below should work.
对于您的用例,下面的代码应该有效。
private static String postProcess(String string) {
String result;
result = string.substring(1,string.length()-1);
return "{" + result + "}";
}
You can parse as a JSON after these steps. 您可以在执行这些步骤后将其解析为JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.