版权声明:希望大家多多指教 https://blog.csdn.net/muriyue6/article/details/81166123
JSON数据的应用
什么是JSON
JSON是一种与开发语言无关的、轻量级的数据格式. 全称 JavaScript Object Notation.
优点: 易于人的阅读和编写, 易于程序解析与生产
标准的JSON数据表示
数据结构 - Object
使用花括号{}包含的键值对结构, Key必须是String类型, Value为任何基本类型或数据结构.
数据结构 - Array
使用中括号[] 来起始, 并用逗号来分隔元素
1、JsonObject封装JSON数据
导入依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
package com.json;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* 封装JSON数据
* Created by gailun on 2018/7/18.
*/
public class JsonObjectSample {
public static void main(String[] args) {
JSONObject();
createJSONObject();
}
/**
* 通过JSONObject对象封装JSON数据
*/
private static void JSONObject(){
JSONObject jsonObject = new JSONObject();
Object nullObj = null;
try {
jsonObject.put("name","奋斗");
jsonObject.put("age",26.8);
jsonObject.put("birthday","1990-01-01");
jsonObject.put("major",new String[]{"敲代码","微商"});
jsonObject.put("girlfriend",false);
jsonObject.put("house",nullObj);
System.out.println(jsonObject.toString());
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 通过Map封装JSON数据
*/
private static void createJSONObject(){
Map<String,Object> jsonObject = new HashMap<>();
jsonObject.put("name","奋斗");
jsonObject.put("age",26.8);
jsonObject.put("birthday","1990-01-01");
jsonObject.put("major",new String[]{"敲代码","微商"});
jsonObject.put("girlfriend",false);
jsonObject.put("house",null);
JSONObject jsonObject1 = new JSONObject(jsonObject);
System.out.println(jsonObject1.toString());
}
//第三中方法是创建一个实体对象, 对象的属性值和map的Key相同,
// 然后把对象的值封装到对象中, 最后把对象放到new JSONObject(对象)中
}
执行结果:
2、JsonObject解析JSON数据
json1文件(在resources目录下):
{
"birthday": "1990-01-01",
"girlfriend": false,
"major": ["敲代码", "微商"],
"name": "奋斗",
"age": 26.8
}
package com.json;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
/**
* 解析JSON数据
* Created by gailun on 2018/7/18.
*/
public class ReadJSONSample {
public static void main(String[] args) throws IOException {
File file = new File(ReadJSONSample.class.getResource("/json1").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = new JSONObject(content);
if (!jsonObject.isNull("name")){
System.out.println("姓名是:"+jsonObject.getString("name"));
}
System.out.println("年龄是: "+jsonObject.getDouble("age"));
System.out.println("有没有女朋友: "+jsonObject.getBoolean("girlfriend"));
JSONArray jsonArray = jsonObject.getJSONArray("major");
for (int i = 0; i < jsonArray.length(); i++) {
String o = (String)jsonArray.get(i);
System.out.println("专业-"+(i+1)+o);
}
}
}
执行结果:
3、通过Gson封装JSON数据
导入依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
package com.json;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* Created by gailun on 2018/7/19.
*/
public class GsonGreateSamp {
public static void main(String[] args) {
Map<String,Object> jsonObject = new HashMap<>();
jsonObject.put("name","奋斗");
jsonObject.put("age",26.8);
jsonObject.put("birthday","1990-01-01");
jsonObject.put("major",new String[]{"敲代码","微商"});
jsonObject.put("girlfriend",false);
jsonObject.put("house",null);
//@SerializedName("")
//Gson gson = new Gson();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field field) {
if (field.getName().equals("name")){
return "NAME";
}
return field.getName();
}
});
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(jsonObject));
}
}
执行结果:
4、通过Gson解析JSON数据
json1文件(在resources目录下):
{
"birthday": "1990-01-01",
"girlfriend": false,
"major": ["敲代码", "微商"],
"name": "奋斗",
"age": 26.8
}
package com.json;
import java.util.Date;
import java.util.List;
/**
* Created by gailun on 2018/7/19.
*/
public class DemoWithBirthday {
private String name;
private double age;
private boolean girlfriend;
private Object house;
private Date birthday;
private List<String> major;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public boolean isGirlfriend() {
return girlfriend;
}
public void setGirlfriend(boolean girlfriend) {
this.girlfriend = girlfriend;
}
public Object getHouse() {
return house;
}
public void setHouse(Object house) {
this.house = house;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<String> getMajor() {
return major;
}
public void setMajor(List<String> major) {
this.major = major;
}
@Override
public String toString() {
return "DemoWithBirthday{" +
"name='" + name + '\'' +
", age=" + age +
", girlfriend=" + girlfriend +
", house=" + house +
", birthday=" + birthday +
", major=" + major +
'}';
}
}
package com.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* Created by gailun on 2018/7/19.
*/
public class GsonReadSample {
public static void main(String[] args) throws IOException {
File file = new File(ReadJSONSample.class.getResource("/json1").getFile());
String content = FileUtils.readFileToString(file);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DemoWithBirthday demoWithBirthday = gson.fromJson(content, DemoWithBirthday.class);
System.out.println(demoWithBirthday);
Gson gson1 = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Map map = gson1.fromJson(content, Map.class);
System.out.println(map);
}
}
执行结果:
5、通过Fastjson封装JSON数据
依赖为:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>
package com.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by gailun on 2018/7/23.
*/
public class FastjsonGreateSample {
public static void main(String[] args) {
Map<String,Object> jsonObject = new HashMap<>();
jsonObject.put("name","奋斗");
jsonObject.put("age",26.8);
jsonObject.put("birthday",new Date());
jsonObject.put("major",new String[]{"敲代码","微商"});
jsonObject.put("girlfriend",false);
jsonObject.put("house",null);
//将Map转成JSON
String string = JSON.toJSONString(jsonObject);
System.out.println(string);
//FastJSON将java.util.Date转成long
String st = JSON.toJSONString(new Date());
System.out.println(st);
//使用SerializerFeature特性格式化日期
String dateJson = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
System.out.println(dateJson);
//指定输出日期格式
String dateJson1 = JSON.toJSONStringWithDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(dateJson1);
}
}
执行结果:
6、通过Fastjson解析JSON数据
package com.json;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* Created by gailun on 2018/7/23.
*/
public class FastjsonReadSample {
public static void main(String[] args) throws IOException {
File file = new File(ReadJSONSample.class.getResource("/json1").getFile());
String content = FileUtils.readFileToString(file);
Map map = JSON.parseObject(content, Map.class);
System.out.println(map);
}
}
执行结果: