json数据根式的转换

string转化为json

1 import org.json.JSONArray;
 2 import org.json.JSONException;
 3 import org.json.JSONObject;
 4 
 5 //别忘了添加上JSON包哦!
 6 public class StringToJSON {
 7     public static void main(String[] args) throws JSONException{
 8         
 9         System.out.println("abc");
10         //定义JSON字符串
11         String jsonStr = "{\"id\": 2," + 
12                 " \"title\": \"json title\", " + 
13                 "\"config\": {" +
14                     "\"width\": 34," +
15                     "\"height\": 35," +
16                 "}, \"data\": [" +
17                     "\"JAVA\", \"JavaScript\", \"PHP\"" +
18                 "]}";
19         
20         //转换成为JSONObject对象
21         JSONObject jsonObj = new JSONObject(jsonStr);
22         
23         //从JSONObject对象中获取数据
24         JavaBean bean = new JavaBean();
25         
26         //根据属性名称获取int型数据;
27         bean.setId(jsonObj.getInt("id"));     
28         
29         //根据属性名获取String数据;
30         bean.setTitle(jsonObj.getString("title")); 
31         
32         //根据属性名获取JSONObject类
33         JSONObject config = jsonObj.getJSONObject("config");
34         bean.setWidth(config.getInt("width"));
35         bean.setHeight(config.getInt("height"));
36         
37         //根据属性名获取JSONArray数组
38         JSONArray data = jsonObj.getJSONArray("data");
39         for(int index = 0, length = data.length(); index < length; index++) {
40             //这里在org.json.JSONArray对象中居然没有找到toArray方法,求各位网友给出解决办法啊!
41 //            bean.setLanguages(String[]);
42         }        
43     }
44 }
45 
46 class JavaBean{
47     private int id ;
48     private String title;
49     private int width;
50     private int height;
51     private String[] languages;
52 
53         //这里省略了设置器和访问器
54 }
 
 
json转化为字符串
 public static void main(String[] args) throws JSONException {
 2         
 3         //创建JSONObject对象
 4         JSONObject json = new JSONObject();
 5         
 6         //向json中添加数据
 7         json.put("username", "wanglihong");
 8         json.put("height", 12.5);
 9         json.put("age", 24);
10         
11         //创建JSONArray数组,并将json添加到数组
12         JSONArray array = new JSONArray();
13         array.put(json);
14         
15         //转换为字符串
16         String jsonStr = array.toString();
17         
18         System.out.println(jsonStr);
19     }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值