java生成json格式数据 和 java遍历json格式数据
来源:互联网 发布:网络招生方案 编辑:程序博客网 时间:2024/06/05 09:06
java 生成json 格式的数据,在需要加入一个创建json的jar包,这个网上有好多,我使用的是org.json的jar包。
- package com.dufy.javatojson;
-
- import java.util.Iterator;
-
- import javax.sound.midi.Synthesizer;
-
- import org.json.JSONArray;
- import org.json.JSONObject;
-
- public class TraverseJson {
-
-
-
-
-
-
- public static Object traveseJson(Object json){
-
- if(json == null){
- return null;
- }
- if(json instanceof JSONObject){
-
- JSONObject jsonObj = new JSONObject();
-
- JSONObject jsonStr = (JSONObject) json;
-
- Iterator it = jsonStr.keys();
- while(it.hasNext()){
-
- String key = (String) it.next();
-
- Object value = jsonStr.get(key);
-
-
- jsonObj.put(key, traveseJson(value));
-
- }
- return jsonObj;
-
- }else if(json instanceof JSONArray){
- JSONArray jsonAry = new JSONArray();
- JSONArray jsonStr = (JSONArray) json;
-
- int length = jsonStr.length();
- for (int i = 0; i <length; i++) {
- jsonAry.put(traveseJson(jsonStr.get(i)));
- }
-
- return jsonAry;
-
- }else {
-
- return json;
- }
-
-
-
- }
-
-
-
- public static void main(String[] args) {
- System.out.println(traveseJson("传入要遍历的json"));
-
-
-
-
-
-
-
-
-
- JSONObject resJsonObj = new JSONObject();
-
- resJsonObj.put("name", "aflyun");
-
- resJsonObj.put("age", 22);
-
- JSONArray arryQq = new JSONArray();
- arryQq.put("742981086@qq.com").put("742981086");
- resJsonObj.put("QQ", arryQq);
-
- JSONObject jsonAdress = new JSONObject();
- jsonAdress.put("国籍", "中国").put("省份", "广东").put("市", "惠州");
- resJsonObj.put("adderss", jsonAdress);
-
- JSONArray jArray = new JSONArray();
- jArray.put("编程").put("看书").put("徒步").put("爬山").put("游泳");
- resJsonObj.put("hobby", jArray);
-
- System.out.println(resJsonObj);
-
- System.err.println(traveseJson(resJsonObj));
-
-
-
-
-
-
-
-
-
-
- JSONArray retJson = new JSONArray();
-
- JSONObject aJosn = new JSONObject();
- aJosn.put("hello", "你好");
- retJson.put(aJosn);
-
- JSONArray jsa = new JSONArray();
- JSONObject jOne = new JSONObject();
- jOne.put("在干嘛", "编程");
- JSONArray jTwo = new JSONArray();
- jTwo.put("没有").put("不想睡").put("");
- JSONObject jOne1 = new JSONObject("醒来了");
- jOne1.put("睡觉了吗", jTwo);
- jsa.put(jOne).put(jOne1);
-
- retJson.put(jsa);
-
- System.out.println("------" + retJson);
- System.err.println("------" + traveseJson(retJson));
-
-
-
- }
-
- }
通过运行上面的代码就能生成我们想要的json格式的数据,如下所示:
- {"QQ":["742981086@qq.com","742981086"],"age":22,"name":"aflyun","hobby":["编程","看书","徒步","爬山","游泳"],"adderss":{"省份":"广东","市":"惠州","国籍":"中国"}}
- ------[{"a":"a"},[{"b":"b"},{"c":[1,2,3]}]]
- {"QQ":["742981086@qq.com","742981086"],"name":"aflyun","age":22,"hobby":["编程","看书","徒步","爬山","游泳"],"adderss":{"省份":"广东","市":"惠州","国籍":"中国"}}
- ------[{"a":"a"},[{"b":"b"},{"c":[1,2,3]}]]