Java 解析JSON

package com.javaer.test;
 
import org.json.JSONException;
import org.json.JSONObject;
 
 
import java.io.IOException;
import java.util.HashMap;
 
public class JSONTtest {
 
 
    public static void main(String[] args) throws JSONException {
        //给我一个json串串,我来解析
        String jsonStr="{\"request\":\"success\",\"age\":18,\"school\":\"北京大学\"}";
 
        JSONObject jsonObj;
        jsonObj = new JSONObject(jsonStr);
        int age = jsonObj.getInt("age");
        String request = (String) jsonObj.get("request");
        System.out.println(age);
        System.out.println(request);
 
       //给我一个HashMap 转换成JSON串串
        HashMap h = new HashMap();
        h.put("name","java-er.com");
        h.put("sex","man");
        JSONObject jsonObj2 = new JSONObject(h);//转化为json格式
 
 
    }
 
 
}

输出

18
success
java-er.com
{"sex":"man","name":"java-er.com"}

Java解析json,如果把数据封装在HashMap再解析,比较方便。

Json依赖包下载

链接:https://pan.baidu.com/s/1RxHQmSAQAAN-qMKPtBj11Q
密码:apy5


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-parse-json/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*