json串解析和生成

平时用gson比较多,有时候不想代码生成实体bean类,然后调用toJson或者fromJson方法。可以用下面简单的方法

如下json串
{
    "os":"android",
    "sv":"Android_SDK_mix_V7.0.0",
    "cv":"1.0.0.000",
    "umid":"F6199D005D38C8BAE0C12DD05D9476EA0334965B",
    "ss":[
        {
            "key":"1",
            "key2":"2",
            "key3":"3"
        }
    ]
}

1.生成json串
用gson来写

       JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("os","android");
        jsonObject.addProperty("sv","Android_SDK_mix_V7.0.0");
        jsonObject.addProperty("cv","1.0.0.000");
        jsonObject.addProperty("umid","F6199D005D38C8BAE0C12DD05D9476EA0334965B");

        JsonArray array = new JsonArray();
        JsonObject jsonObject1 = new JsonObject();
        jsonObject1.addProperty("key","1");
        jsonObject1.addProperty("key2","2");
        jsonObject1.addProperty("key3","3");
        array.add(jsonObject1);

        jsonObject.add("items",array);

用org.json包来写

try {
            JSONObject jsonObject2 = new JSONObject();

            jsonObject2.put("os", "android");
            jsonObject2.put("sv", "Android_SDK_mix_V7.0.0");
            jsonObject2.put("cv", "1.0.0.000");
            jsonObject2.put("umid", "F6199D005D38C8BAE0C12DD05D9476EA0334965B");
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObjectProductInfo = new JSONObject();
            jsonObjectProductInfo.put("key", "1");
            jsonObjectProductInfo.put("key2", "2");
            jsonObjectProductInfo.put("key3", "3");
            jsonArray.put(jsonObjectProductInfo);
            jsonObject2.put("items", jsonArray);
            Log.i("test",jsonObject2.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

2.解析json串
用gson

        JsonObject jsonObject2 = new JsonParser().parse(json).getAsJsonObject();
        Log.i("test", jsonObject2.get("os").getAsString());
        Log.i("test", jsonObject2.get("sv").getAsString());
        Log.i("test", jsonObject2.get("umid").getAsString());


        JsonArray items = jsonObject2.getAsJsonArray("items");
        JsonObject asJsonObject = items.get(0).getAsJsonObject();
        Log.i("test", asJsonObject.get("key").getAsString());

用org.json包来写

try {
            JSONObject js = new JSONObject(json);
            Log.i("test",js.optString("os")) ;
            Log.i("test",js.getString("sv")) ;
            JSONArray items = js.getJSONArray("items");
            JSONObject jsonObject2 = items.getJSONObject(0);
            Log.i("test",(String)jsonObject2.optString("key")) ;
        } catch (JSONException e) {
            e.printStackTrace();
        }

你可能感兴趣的:(json串解析和生成)