json字符串及json对象之间互相转换

在开发中经常遇到json对象及json字符串之间的转换,今天,总结一下三种不同jar包下的互相转换。

1:导入com.alibaba.fastjson.JSONObject:

json对象和json字符串相互转换代码如下:

import com.alibaba.fastjson.JSONObject;
public class Test2Controller {
    public static void main(String[] args) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("1","小明");
            jsonObject.put("2","小红");
            System.out.println(jsonObject.toJSONString());
            System.out.println(jsonObject.toString());
            String str2 = "{\"1\":\"数学\",\"2\":\"语文\"}";
            JSONObject jsonObject1 = JSONObject.parseObject(str2);
            System.out.println(jsonObject1);
           }
}

可以看到上述代码,将json对象转换为json字符串的时候,有toJSONString和toString两种方法,输出结果是相同的,于是打开toString方法,看源码,发现toString底层也是调用的toJSONString方法,toString方法源码如下:

 @Override
    public String toString() {
        return toJSONString();
    }

    public String toJSONString() {
        SerializeWriter out = new SerializeWriter();
        try {
            new JSONSerializer(out).write(this);
            return out.toString();
        } finally {
            out.close();
        }
    }

2:导入org.json.*:

json对象和json字符串相互转换代码如下:

import org.json.*;
	public class TestController {
	    public static void main(String[] args) {
	        JSONObject jsonObject = new JSONObject();
	        jsonObject.put("1","小明");
	        jsonObject.put("2","小花");
	        jsonObject.put("3","小红");
	        //将json对象转换为json字符串
	        String str = jsonObject.toString();
	        System.out.println(str);
	        //将json字符串转换为json对象
	        String str2 = "{\"1\":\"数学\",\"2\":\"语文\"}";
	        JSONObject jsonObject1 = new JSONObject(str2);
	        System.out.println(jsonObject1);
	    }
	}

3:导入net.sf.json.JSONObject:

json对象和json字符串相互转换代码如下:

import net.sf.json.JSONObject;
public class Test3Controller {
    public static void main(String[] args) {
        //json对象转换为json字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("1","小明");
        jsonObject.put("2","小红");
        System.out.println(jsonObject.toString());
        //json字符串转换为json对象
        String str = "{\"1\":\"语文\",\"2\":\"数学\"}";
        JSONObject jsonObject1 = JSONObject.fromObject(str);
        System.out.println(jsonObject1);
    }
}

以上三种不同jar包下的json对象及json字符串之间转换,json对象转换为json字符串都是调用toString方法。json字符串转换为json对象三种写法有所区别。

 

 

猜你喜欢

转载自blog.csdn.net/qq_36833673/article/details/106237969
今日推荐