美文网首页
Json格式String转dto对象类

Json格式String转dto对象类

作者: BestFei | 来源:发表于2020-06-21 14:46 被阅读0次

一、定义dto

package test.bestfei.dto;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class PremierLeagueTable {

    @ApiModelProperty("rank")
    private int rank;

    @ApiModelProperty("team")
    private String team;

    @ApiModelProperty("points")
    private int points;

}

二、代码实现
转成List,并按rank字段排序

package test.futures.bestfei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.stream.Collectors;
import test.bestfei.dto.PremierLeagueTable;


    @Test
    public void testStringToJsonList(){
        String s = "[{\"rank\":1,\"team\":\"Liverpool\",\"points\":100}," +
                "{\"rank\":2,\"team\":\"Arsenal\",\"points\":98},\n" +
                "{\"rank\":4,\"team\":\"Chelsea\",\"points\":90},\n" +
                "{\"rank\":3,\"team\":\"Manchester Utd\",\"points\":97}]";
        List<PremierLeagueTable> ranks = JSON.parseObject(s, new TypeReference<List<PremierLeagueTable>>() {
        });

        System.out.println("sort rank");
        ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getRank)).collect(Collectors.toList());
        for(int i=0;i<ranks.size();i++){
            System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
        }

        System.out.println("sort reversed rank");
        ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getRank).reversed()).collect(Collectors.toList());
        for(int i=0;i<ranks.size();i++){
            System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
        }

        System.out.println("sort points");
        ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getPoints)).collect(Collectors.toList());
        for(int i=0;i<ranks.size();i++){
            System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
        }
    }

相关文章

网友评论

      本文标题:Json格式String转dto对象类

      本文链接:https://www.haomeiwen.com/subject/vbfaxktx.html