2011-10-06 83 views
0

的Json包含在String str字符串:的Android解析JSON文件

{conf:{"quantity_uom":"l",price_uom:"euro",distance_uom:"km",consumption_uom:"km/l"}} 

代码:

try{ 
     if (str!=""){ 
      this.json = new JSONObject(str); 
      this.quantityUom=this.json.getString("quantity_uom"); 
      this.distanceUom=this.json.getString("distance_uom"); 
      this.priceUom=this.json.getString("price_uom"); 
      this.consumptionUom=this.json.getString("consumption_uom");    
     } 
    }catch (Exception e) { 
     throw e; 
    } 

我回来了No value for quantity_uom。我怎么做错了?字符串包含json文本。

非常感谢。

+0

'str!=“”'不能用于Java/Android。使用这个:'!str.equals(“”)' – WarrenFaith

+0

你的字符串不是有效的JSON。 – JeremyP

回答

4
try{ 
    if (!str.equals("")){ 
     Json obj = new JSONObject(str); 
     this.json = obj.getJSONObject("conf"); 
     this.quantityUom=this.json.getString("quantity_uom"); 
     this.distanceUom=this.json.getString("distance_uom"); 
     this.priceUom=this.json.getString("price_uom"); 
     this.consumptionUom=this.json.getString("consumption_uom");    
    } 
}catch (Exception e) { 
    throw e; 
} 

你首先要得到的字符串,并从JSON对象获得其他值命名为 '的conf' JSON对象。

1

JSON字符串不正确。

试试这个:

{"conf":{"quantity_uom":"l","price_uom":"euro","distance_uom":"km","consumption_uom":"km/l"}}