fastjson maven示例分享
下文是笔者基于maven项目制作的fastjson示例分享,如下所示
实现思路: 1.引入相应的maven坐标 2.import相应的代码,然后编写相应的代码即可例:
fastjson坐标 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency> 示例代码 package com.java265; import java.util.Arraylist; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; public class TestFastJson { static class User{ private String id ; private String name; private int age ; public User(){ } public User(String id,String name,int age){ this.id=id; this.name=name; this.age=age; } public String getId() { return id; } public void setId(String id) { this.id = id; } 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; } @Override public String toString() { return "User [age=" + age + ", id=" + id + ", name=" + name + "]"; } } public static void main(String[] args) { method1(); method2(); method3(); method4(); } static void method1(){ System.out.println("javabean转化示例开始----------"); User User = new User("1","java265",1); //这里将javabean转化成json字符串 String jsonString = JSON.toJSONString(User); System.out.println(jsonString); //这里将json字符串转化成javabean对象, User =JSON.parseObject(jsonString,User.class); System.out.println(User.toString()); System.out.println("javabean转化示例结束----------"); } static void method2(){ System.out.println("List<javabean>转化示例开始----------"); User User1 = new User("1","java265-1",1); User User2 = new User("2","java265-2",2); List<User> Users = new ArrayList<User>(); Users.add(User1); Users.add(User2); String jsonString = JSON.toJSONString(Users); System.out.println("json字符串:"+jsonString); //解析json字符串 List<User> Users2 = JSON.parseArray(jsonString,User.class); //输出解析后的User对象,也可以通过调试模式查看Users2的结构 System.out.println("User1对象:"+Users2.get(0).toString()); System.out.println("User2对象:"+Users2.get(1).toString()); System.out.println("List<javabean>转化示例结束----------"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。