2017-10-16 111 views
0
正确的价值观

您好我试图解析JSON,如:JSON解析不会放弃使用GSON

{"error":{"code":20,"message":"Transaction not found."}} 

所使用的代码是:

GulfBoxError errordetails= new Gson().fromJson(json, GulfBoxError.class); 
       System.out.println("RESULT :"+errordetails.getCode()+" "+errordetails.getMessage()); 

类文件:

public class GulfBoxError { 
public int code; 
public String message; 

public int getCode() { 
    return code; 
} 
public String getMessage() { 
    return message; 
} 
} 

每当我尝试,我没有得到他在这里值:

RESULT :0 null 

任何想法为什么?我在这里丢失的东西

+1

[JSON解析错误使用gson]的可能重复(https://stackoverflow.com/questions/9915141/json-parse-error-using-gson) – Balasubramanian

+0

@ErikKralj什么错误属性? – Karthi

+0

@Balasubramanian。这不是重复的!问题可能似乎重复,但其实际上不同! – Karthi

回答

0
  • 如果不封装字段,则不需要获取者。
  • 你的对象是邮件形成的。顶级应只包含一个字段:error

代码应该是这样的:

public class GufError{ 
    public GulfBoxError error; 
} 

public class GulfBoxError { 
    public int code; 
    public String message; 

    public int getCode() { 
     return code; 
    } 

    public String getMessage() { 
     return message; 
    } 
} 
GufError errordetails= new Gson().fromJson(json, GufError.class); 
+0

为什么它会这样做!我多次使用上述方法,并成功!这种情况只发生在这种情况下 – Karthi

+0

是的!愚蠢的错误!让我检查一下 – Karthi

0

你可以试试这个,如果你不希望创建一个单独的类的包装:

Gson gson = new Gson(); 
JsonObject jsonObj = gson.fromJson(json,JsonObject.class); 
GulfBoxError errordetails= gson.fromJson(jsonObj.get("error"), GulfBoxError.class); 
System.out.println("RESULT :"+errordetails.getCode()+" "+errordetails.getMessage()); 
0

您的GulfBoxError类不正确。

你需要的东西是这样的:

public class GulfError{ 
    public GulfBoxError error; 
} 

class GulfBoxError { 
    public int code; 
    public String message; 

    public int getCode() { 
     return code; 
    } 

    public String getMessage() { 
     return message; 
    } 
} 

并解析它以这样的方式

Gson gson = new Gson(); 
    String filename="/...Pathtoyour/json.json"; 
    JsonReader reader = new JsonReader(new FileReader(filename)); 
    GulfError errordetails= gson.fromJson(reader, GulfError.class); 
    System.out.print("errordetails: " + gson.toJson(errordetails)); 

无论如何,如果你想用你的GulfBoxError类,你可以这样做:

 Type listType = new TypeToken<Map<String, GulfBoxError>>(){}.getType(); 
     Map<String, GulfBoxError> mapGulfBoxError= gson.fromJson(reader,listType); 
     for (Map.Entry<String, GulfBoxError> entry : mapGulfBoxError.entrySet()) 
     { 
      System.out.println("Key: " + entry.getKey() + "\nValue:" + gson.toJson(entry.getValue())); 

     } 

有时候,如果你不想创建完全代表Json的对象,这可能会很有用。