fastjson简单使用

fastjson来源于alibaba,将任意类型转化为json格式

fastjson推荐版本

              <!--添加fastjson依赖-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.70</version>
		</dependency> 

 本次项目采用两个springboot项目完成,以为很多时候都是调用了第三方接口,我们需要从返回的参数中获取我们需要的数据

springboot项目创建两种形式,一种是https://start.spring.io/创建,另一种是idea创建

使用地址创建

 

 

 一般情况我会先用idea创建maven工程,然后加入需要的依赖

 

实现将字符串转化为集合

 

 接口所在的项目代码

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com</groupId>
	<artifactId>java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>fastjson-study</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

  

package com.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FastjsonStudyApplication {

	public static void main(String[] args) {
		SpringApplication.run(FastjsonStudyApplication.class, args);
	}

}

  

package com.java.bean;


import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Data
@Builder
public class ClassRoom implements Serializable {

    private String name;

    private String hobby;

    private String address;
}

  

package com.java.controller.front;

import com.java.bean.ClassRoom;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class JsonController {


    @GetMapping("/getList")
    public List<ClassRoom> getList(){

        List<ClassRoom> classRoomList=new ArrayList<>();
        classRoomList.add(ClassRoom.builder().name("小六子").hobby("羽毛球").address("快乐星球").build());
        classRoomList.add(ClassRoom.builder().name("小黑子").hobby("足球").address("火星").build());
        classRoomList.add(ClassRoom.builder().name("小红子").hobby("橄榄球").address("M78星云").build());
        return classRoomList;

    }
}

  调用方代码

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.java</groupId>
    <artifactId>fastjson-study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

  

package com.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author yourheart
 * @Description
 * @create 2022-07-12 22:11
 */
@SpringBootApplication
public class FastJsonApplication {
    public static void main(String[] args) {
        SpringApplication.run(FastJsonApplication.class,args);
    }
}

  

package com.java.bean;


import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

@Data
public class ClassRoom{

    private String name;

    private String hobby;

    private String address;
}

  

package com.java.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;

/**
 * @author yourheart
 * @Description
 * @create 2022-07-12 22:22
 */

@Configuration
public class RestTemplateConfig {


    /**
     * 处理中文乱码问题
     * @return
     */
    @Bean
    public RestTemplate utp8RestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }


}

  测试类的对应代码

package com.java;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.TypeReference;
import com.java.bean.ClassRoom;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;


/**
 * @author yourheart
 * @Description
 * @create 2022-07-12 22:14
 */

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class FastJsonApplicationTests {

    @Autowired
   private RestTemplate restTemplate;

    @Test
    public void test(){
        String url="http://127.0.0.1:4001/getList";
        String result = restTemplate.getForObject(url, String.class);
        log.info("result:{}",result);

        //因为result的实际格式是list,所以我们要实现字符串转化为集合
        ArrayList<ClassRoom> classRoomArrayList  = JSON.parseObject(result, new TypeReference<ArrayList<ClassRoom>>(){});
        classRoomArrayList.forEach(a->{
            log.info(a.toString());
        });
    }
}

  

 

 测试类

package com.java;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;


/**
 * @author yourheart
 * @Description
 * @create 2022-07-12 22:14
 */

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class FastJsonApplicationTests {

    @Test
    public void jsonTest(){
        //新建json对象
        JSONObject jsonObject=new JSONObject();

        //向对象中填充数据
        jsonObject.put("name1","qwe");
        jsonObject.put("name2","asd");
        jsonObject.put("name3","zxc");

        //取值
        String name1 = jsonObject.getString("name1");
        log.info("【取值】name1:{}",name1);

        //转化为json字符串
        String jsonString = jsonObject.toJSONString();
        log.info("【json转化为json字符串】jsonString:{}",jsonString);

        //map集合转化为json
        Map<String,Object> map=new HashMap<>();
        map.put("userName","admin");
        map.put("pwd","123456");
        JSONObject object = new JSONObject(map);
        log.info("【map集合转化为json】object:{}",object);

        //json转化为map
        JSONObject json = new JSONObject();
        json.put("username", "yaomy");
        json.put("password", "123");
        Map<String, Object> resultMap = (Map<String, Object>)json;
        log.info("【json转化为map】resultMap:{}",resultMap);

        //字符串转化为json
        String str = "{\"username\":\"admin\",\"password\":\"123\"}";
        JSONObject jsonObject1 = JSONObject.parseObject(str);
        log.info("【字符串转化为json】jsonObject1:{}",jsonObject1);

    }

}

  字符串转JsonArray

String a="[\"11\"]";
JSONArray objects = JSONObject.parseArray(a);

  从数组中取数据

 

 

package com.java;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class Tests {

    @Test
    public void test(){
       String a="[\"11\"]";
        JSONArray objects = JSONObject.parseArray(a);
        log.info("objects:{}",objects);
        Object[] objects1 = objects.toArray();
        log.info(objects1[0].toString());

    }
}

  map集合转化为字符串

Map<String,Object> map=new HashMap<>();
map.put("name","test");
String toJSONString=JSONUtils.toJSONString(map)

  集合和字符串的转化

package com.java.test.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/11/1 21:53
 */
@Slf4j
public class FastjsonDemo {
    @Test
    public void arrayTest(){
        List<Animal> animalList=new ArrayList<>();
        Animal animal=new Animal();
        animal.setId("12");
        animal.setName("小白");
        animal.setAge("2");
        Animal animal1=new Animal();
        animal1.setId("12");
        animal1.setName("小白");
        animal1.setAge("2");
        animalList.add(animal);
        animalList.add(animal1);
        //将集合转化为字符串
        String toJSONString = JSON.toJSONString(animalList);
        log.info("【将集合转化为字符串】toJSONString:{}",toJSONString);
        //字符串转化为集合
        ArrayList<Animal>  listAnimals = JSON.parseObject(toJSONString, new TypeReference<ArrayList<Animal>>() {
        });
        log.info("【字符串转化为集合】listAnimals:{}",listAnimals);
        //字符串转化为集合
        List<Animal> list = JSONObject.parseArray(toJSONString, Animal.class);
        log.info("【字符串转化为集合】list:{}",list);
    }
}

  

 

package com.java.test.fastjson;

import lombok.Data;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/11/1 22:22
 */
@Data
public class Animal {

    private String id;

    private String name;

    private String age;
}

  

 

posted @ 2022-07-12 23:02  不忘初心2021  阅读(313)  评论(0编辑  收藏  举报