Fastjson JSON 操作

2018-11-28  本文已影响0人  风清云流

Fastjson JSON 操作

1. Java环境下使用

1.1 Json字符串转为json对象

将下面的json字符串转为json对象,同时对该对象析构。

{
    "code": "200",
    "message": "SUCCESS",
    "data": [
        {
            "name": "lisi",
            "age": 32
        },
        {
            "name": "liwu",
            "age": 23
        }
    ]
}

程序:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

public class Exercise {

    @Test
    public void stringToJson() {
        // json压缩转义网址:https://www.bejson.com/zhuanyi/
        String jsonStr = "{\"code\":200,\"message\":\"SUCCESS\",\"data\":[{\"name\":\"lisi\",\"age\":32}," +
                "{\"name\":\"liwu\",\"age\":23}]}";
        JSONObject parse = (JSONObject) JSON.parse(jsonStr);
        int code = (int) parse.get("code");
        String message = (String) parse.get("message");
        System.out.println(code);
        System.out.println(message);
        JSONArray dataArray = parse.getJSONArray("data");
        for (Object obj : dataArray) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(obj);
            String name = (String) jsonObject.get("name");
            int age = (int) jsonObject.get("age");
            System.out.println("[name: " + name + ", age: " + age + "]");
        }

    }
}

运行结果:

200
SUCCESS
[name: lisi, age: 32]
[name: liwu, age: 23]

1.2 Bean对象转为json对象

程序1:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

/*    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }*/
}

public class Exercise {

    @Test
    public void stringToJson() {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonObject.put("code", 200);
        jsonObject.put("message", "SUCCESS");
        jsonArray.add(new Person("lisi", 32));
        jsonArray.add(new Person("liwu", 23));
        jsonObject.put("data", jsonArray);
        System.out.println(jsonArray);
        System.out.println(jsonObject);
        System.out.println("-----------");
        int code = (int) jsonObject.get("code");
        String message = (String) jsonObject.get("message");
        System.out.println(code);
        System.out.println(message);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        for (Object obj : dataArray) {
            JSONObject json = (JSONObject) JSONObject.toJSON(obj);
            String name = (String) json.get("name");
            int age = (int) json.get("age");
            System.out.println("[name: " + name + ", age: " + age + "]");
        }

    }
}

运行结果:

[{},{}]
{"code":200,"data":[{},{}],"message":"SUCCESS"}
-----------
200
SUCCESS

java.lang.NullPointerException
    at cn.ouyxy.operation.Exercise.stringToJson(Exercise.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at...

程序2:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Exercise {

    @Test
    public void stringToJson() {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonObject.put("code", 200);
        jsonObject.put("message", "SUCCESS");
        jsonArray.add(new Person("lisi", 32));
        jsonArray.add(new Person("liwu", 23));
        jsonObject.put("data", jsonArray);
        System.out.println(jsonArray);
        System.out.println(jsonObject);
        System.out.println("-----------");
        int code = (int) jsonObject.get("code");
        String message = (String) jsonObject.get("message");
        System.out.println(code);
        System.out.println(message);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        for (Object obj : dataArray) {
            JSONObject json = (JSONObject) JSONObject.toJSON(obj);
            String name = (String) json.get("name");
            int age = (int) json.get("age");
            System.out.println("[name: " + name + ", age: " + age + "]");
        }

    }
}

运行结果:

[{"age":32,"name":"lisi"},{"age":23,"name":"liwu"}]
{"code":200,"data":[{"age":32,"name":"lisi"},{"age":23,"name":"liwu"}],"message":"SUCCESS"}
-----------
200
SUCCESS
[name: lisi, age: 32]
[name: liwu, age: 23]

2. Scala环境下使用

2.1 Json字符串转为json对象

程序:

import com.alibaba.fastjson.{JSON, JSONObject}

object Exercise2 {
    def main(args: Array[String]): Unit = {
        val jsonStr =
            """
              |{
              |    "code": "200",
              |    "message": "SUCCESS",
              |    "data": [
              |        {
              |            "name": "lisi",
              |            "age": 32
              |        },
              |        {
              |            "name": "liwu",
              |            "age": 23
              |        }
              |    ]
              |}
            """.stripMargin

        val jsonObject = JSON.parse(jsonStr).asInstanceOf[JSONObject]
        val code = jsonObject.get("code")
        val message = jsonObject.get("message")
        println(code)
        println(message)
        val data = jsonObject.getJSONArray("data")
        for(i <- 0 until data.size){
            val obj = data.getJSONObject(i)
            val name = obj.get("name")
            val age = obj.get("age")
            println("[name: " + name + ", age: " + age + "]")
        }
    }
}

运行结果:

200
SUCCESS
[name: lisi, age: 32]
[name: liwu, age: 23]

2.2 fastjson序列化scala对象

程序1:

import com.alibaba.fastjson.JSON

case class Cat(name: String, age: Int)

object Exercise2 {
    def main(args: Array[String]): Unit = {
        val cat = Cat("mao1", 1)
        val str = JSON.toJSONString(cat, false)
        println(str)
    }
}

结果:

{}

结果解析:
fastjson默认是基于方法clz.getMethods()进行字段查找过滤的,通过getter方法查找字段信息;而这里使用case class方式构建对象,没有settergetter方法,使用默认的配置序列化对象,导致错误。根据这个思路,为Cat类加上 getter,可以解决问题,如程序2

程序2:

import com.alibaba.fastjson.JSON

class Cat(_name: String, _age: Int){
    var name: String = _name
    val age: Int = _age

    def getName = this.name
    def getAge = this.age
}

object Cat{
    def apply(_name: String, _age: Int): Cat = new Cat(_name, _age)
}

object Exercise2 {
    def main(args: Array[String]): Unit = {
        val cat = Cat("mao1", 1)
        val str = JSON.toJSONString(cat, false)
        println(str)
    }
}

运行结果:

{"age":1,"name":"mao1"}

fastjson 同时提供了基于字段的方式clz.getDeclaredFields()进行查找过滤。修改后的代码如程序3:

程序3:

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializeConfig

case class Cat(name: String, age: Int)

object Exercise2 {
    def main(args: Array[String]): Unit = {
        val cat = Cat("mao1", 1)
        val conf = new SerializeConfig(true)
        val str = JSON.toJSONString(cat, conf)
        println(str)
    }
}

结果:

{"age":1,"name":"mao1"}

2.3 scala对象转为json对象

程序:

import com.alibaba.fastjson.{JSON, JSONArray}
import com.alibaba.fastjson.serializer.SerializeConfig
import scala.collection.JavaConversions._

case class Cat(name: String, age: Int)

object Exercise2 {
    def main(args: Array[String]): Unit = {

        val conf = new SerializeConfig(true)
        val catList = List(JSON.toJSON(Cat("mao1", 1), conf), JSON.toJSON(Cat("mao2", 1), conf))
        val jsonArray: JSONArray = new JSONArray(catList)
        println(jsonArray)
    }
}

运行结果:

[{"name":"mao1","age":1},{"name":"mao2","age":1}]
上一篇下一篇

猜你喜欢

热点阅读