简体   繁体   English

JSON简单的ClassCastException,从String到JSONObject

[英]JSON-simple ClassCastException from String to JSONObject

I have an Array of JSON Objects like this: 我有这样的JSON对象数组:

{"message":"[\"{\\\"name\\\":\\\"lays\\\",\\\"calories\\\":1.0}\",\"{\\\"name\\\":\\\"lays\\\",\\\"calories\\\":0.33248466}\"]"}

I am trying to parse it using this code: 我正在尝试使用以下代码来解析它:

Object object = parser.parse ( message );
JSONArray array = (JSONArray) object;
for(int i=0;i < array.size () ; i++)
{
    System.out.println(array.get ( i ));//output; {"name":"lays","calories":1.0}
    JSONObject jsonObj = ( JSONObject ) array.get ( i );//ClassCastExceptio
    String foodName = ( String ) jsonObj.get ( KEY_NAME );
    Float calories = (Float) jsonObj.get ( KEY_CARLORIES );
    Nutrinfo info = new Nutrinfo(foodName,calories);
    data.add ( info );

}

but I get a ClassCastException on the marked line. 但我在标记的行上收到ClassCastException。 This doesn't make sense: array.get() returns an object, which I cast to a JSONObject. 这没有道理:array.get()返回一个对象,我将其强制转换为JSONObject。 Why am I getting this error. 为什么我会收到此错误。

Thanks. 谢谢。

You have multiple json objects within the "message" json object. 您在“ message” json对象内有多个json对象。 Use this code to retreve the first values (need a loop for all of them). 使用此代码检索第一个值(所有它们都需要循环)。 It seems like you may want to rearrange how you are creating your json objects. 似乎您可能想重新排列创建json对象的方式。

Object object = parser.parse ( message );
JSONArray array = (JSONArray) object;
for(int i=0;i < array.size () ; i++)
{
JSONArray jsonArray = ( JSONArray ) array.get ( i );
JSONObject jsonObj = (JSONObject) jsonArray.get(0);
String foodName = jsonObj.getString ( KEY_NAME );
Float calories = jsonObj.getFloat ( KEY_CARLORIES );
Nutrinfo info = new Nutrinfo(foodName,calories);
data.add ( info );
}

Remember when using JSON, each {} set of brackets signifies an individual JSON object. 请记住,使用JSON时,每套{}括号都表示一个单独的JSON对象。 When dealing with multiple objects on the same level, you must first get the JSON Array (like you did for each message). 在同一级别上处理多个对象时,必须首先获取JSON数组(就像对每条消息所做的一样)。

You have json content embedded within json content. 您将json内容嵌入json内容中。 the "outer" object has a key "message" with a single string value . “外部”对象具有带有单个字符串值的键"message" that string value happens to be serialized json, but the json parser isn't going to handle that for you automatically. 该字符串值恰好是序列化的json,但json解析器不会自动为您处理。 you will have to get the message value and parse that a second time. 您将必须获取消息值并再次进行解析。 (actually, it's worse than that, you have at least 2 levels of embedded json content). (实际上,更糟糕的是,您至少有2个级别的嵌入式json内容)。

Object object = parser.parse ( message );

if( object instanceof JSONObject ){
    // TODO : process with single JSON Object
}
else if( object instanceof JSONArray ){
    // TODO : process with JSONArray Object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM