1.下面我们来说一下如何构建我们需要的json字符串

JSONObject 可以放key和value的形式为(String,object),也就是key的类型为String字符串,value的形式是object

表现形式为:

 {

"key":value,

"key":value

}

JSONArray 放的值为JSONObject ,可以指定index也就是JSONObject值的顺序

表现形式为:

 [

        {

        "key":value,

        "key":value

        },

        {

        "key":value,

        "key":value

        }

]

举个例子:

如果我们想构建一个如下的json字符串

{

    "error": 0,

    "status": "success",

    "results": [

        {

            "currentCity": "青岛",

            "index": [

                {

                    "title": "穿衣",

                    "zs": "较冷",

                    "tipt": "穿衣指数",

                    "des": "建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。"

                },

                {

                    "title": "紫外线强度",

                    "zs": "中等",

                    "tipt": "紫外线强度指数",

                    "des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"

                }

            ]

        }

    ]

}

最外层是JSONObject,results的值为JSONArray,results里边的index的值为JSONArray

//最外层JSONObject   

JSONObject   object = new JSONObject();

//results的JSONArray

JSONArray  resultsArray = new JSONArray();

//results里边的JSONObject   

JSONObject   resultObject = new JSONObject();

//index里边的JSONArray

JSONArray  indexArray = new JSONArray();

//index里边的JSONObject   

JSONObject   indexObject1 = new JSONObject();

JSONObject   indexObject2 = new JSONObject();

indexObject1.put("title","穿衣");

......

indexObject2.put("title","紫外线强度");

......

//开始组合json串

indexArray.put(indexObject1);

indexArray.put(indexObject2);

resultObject.put("currentCity","青岛");

resultObject.put("index",indexArray );

resultsArray.put(resultObject );

//放入object 的数据

object.put("error",0);

object.put("status","success");

object.put("results",resultsArray);

//构建完成

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐