gpt4 book ai didi

java - 尝试从 JSON 文件创建对象时出现 MalformedJsonException

转载 作者:行者123 更新时间:2023-12-01 20:52:39 26 4
gpt4 key购买 nike

我在从 Json 文件创建对象时遇到问题。我有三个类,GsonReader 处理创建对象,一个是 POJO 类 Model 和一个 Main 方法类,我在其中调用 GsonReader 的方法,您能告诉我我的代码有什么问题,并提供一些解释吗?

已编辑

GsonReader

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;

public class GsonReader {

private String path = "D:\\ImportantStuff\\Validis\\Automation\\json.txt";

public void requestGson() throws FileNotFoundException {
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
JsonReader reader = new JsonReader(new FileReader(path));
//BufferedReader reader = new BufferedReader(new FileReader(path));
Object json = gson.fromJson(reader, Model.class);
System.out.println(json.toString());
}
}

主要

import java.io.FileNotFoundException;

public class Main {

public static void main(String[] args) throws FileNotFoundException {
GsonReader r = new GsonReader();
r.requestGson();

}

}

型号

public class Model {
private String name;
private String type;
private String value;

public Model(String name, String type, String value){
this.name = name;
this.type = type;
this.value = value;
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public String getType(){
return type;
}

public void setType(String type){
this.type = type;
}

public String getValue(){
return value;
}

public void setValue(String value){
this.value = value;
}
}
public String toString(){
return "Name: " + name + "\n" + "Type: " + type + "\n" + "Value: " + value;
}

Json

{
'name': 'Branding',
'type': 'String',
'value': 'Tester'
}

最佳答案

在所有内容周围使用标准引号和逗号:-

{
"name": "example",
"type": "example",
"value": "example"
}

现在根据 http://json.parser.online.fr/ 进行验证.

关于java - 尝试从 JSON 文件创建对象时出现 MalformedJsonException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com