没有用过这种数据格式,
比如说这样一段数据"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"}
这是从js中拿出来的,
怎么写就能在后台中这样得到jsonObj.getJSONObject("ingredients").get("apples"),然后后台输出3KG

解决方案 »

  1.   

    首先一个json的一个转换类
    public class JsonTools { public static String encode(Object data) { JSONObject jsonObject = JSONObject.fromObject(data, getJsonConfig());
    String reqMsg = jsonObject.toString();
    return reqMsg;
    } public static Object decode(String data, Class beanClass) {
    JSONObject json = JSONObject.fromObject(data, getJsonConfig());
    return JSONObject.toBean(json, beanClass);
    } public static String getPojoData(Object data) {
    JSONObject jsonObject = JSONObject.fromObject(data, getJsonConfig());
    return jsonObject.getString("pojoObject");
    } private static JsonConfig getJsonConfig() 
    {
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerDefaultValueProcessor(Integer.class, new DefaultValueProcessor() {
    public Object getDefaultValue(Class type) {
    return null;
    }
    });
    jsonConfig.registerDefaultValueProcessor(BigInteger.class, new DefaultValueProcessor() {
    public Object getDefaultValue(Class type) {
    return null;
    }
    });
    jsonConfig.registerDefaultValueProcessor(String.class, new DefaultValueProcessor() {
    public Object getDefaultValue(Class type) {
    return null;
    }
    });
    jsonConfig.registerDefaultValueProcessor(Boolean.class, new DefaultValueProcessor() {
    public Object getDefaultValue(Class type) {
    return null;
    }
    });
    jsonConfig.registerDefaultValueProcessor(Long.class, new DefaultValueProcessor() {
    public Object getDefaultValue(Class type) {
    return null;
    }
    });
    return jsonConfig;
    }
    }你上面的"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"}
    是通过:
    // 对数据进行Json编码
    dataBody = JsonTools.encode(ingredients对象实例);得到的。reqBean就是你的Ingredients对象
    // 将json字符串解码为ingredients对象如下
    Ingredients reqBean=(Ingredients)JsonTools.decode(“你上面的字符串”,Ingredients.class);写上面那个类需要导入一个json的包json-lib-2.3-jdk15.jar
      

  2.   

    不用这么麻烦。。直接转换为ingredients,然后通过get方法取就行了节省代码量,防止属性名称写错而引起不必要的错误
      

  3.   

    好像直接把这个string通过new jsonobject(string)转成jsonobj,然后getJSONObject("ingredients"),得到的jsonobj就可以调get("apples")获取到你要的值了吧