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

时间:2017-03-23 12:10:11

标签: java json gson

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

EDITED

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'
}

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

使用逗号分隔您的JSON属性并使用适当的引号。

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

答案 2 :(得分:0)

{
  “name”: example,
  “type”: example,
  “value”: example
}

JSON格式错误。

对于字符串属性,它必须是:

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

另外,我对Gson不太熟悉,但设置:

setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)

应该是吗?

 {
   "Name": "example",
   "Type": "example",
   "Value": "example"
 }