java----JSON

 JSON:

下载组件 GSON jar 包

https://mvnrepository.com/artifact/com.google.code.gson/gson

创建JSON

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.io.*;
import java.util.ArrayList;


public class Demo {
    public static void main(String[] args) throws IOException {
        createJson();
    }
    public static void createJson(){
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person("花花",10));
        list.add(new Person("哈哈",12));
        JsonArray jsonElements = new JsonArray();
        for (int i = 0; i < list.size(); i++) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name",list.get(i).getName());
            jsonObject.addProperty("age",list.get(i).getAge());
            jsonElements.add(jsonObject);
        }
        //
        System.out.println(jsonElements.toString());
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("a.json"));
            bw.write(jsonElements.toString());
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Person{
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person() {
    }
    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 "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  

解析json数据(适合解析复杂的json数据)

必须严格准守解析流程,中途如果出现错误,就会发生解析失败

[]  : beginArray;

{} : beginObject;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import java.io.*;
import java.util.ArrayList;

public class Demo {
    public static void main(String[] args){
        jsonParse();
    }
    public static void jsonParse(){
        try {
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("json\\person_json.json");
            InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
            //json解释工具a
            JsonReader jsonReader = new JsonReader(inputStreamReader);
            ArrayList<Person> nameList = new ArrayList<>();
            //开始解析数组
            jsonReader.beginArray();
            while (jsonReader.hasNext()){
                nameList.add(parsePerson(jsonReader));
            }
            //结束解析数组
            jsonReader.endArray();
            nameList.forEach((p)-> System.out.println(p));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static Person parsePerson(JsonReader jsonReader) throws IOException {
        Person person = new Person();
        jsonReader.beginObject();
        while (jsonReader.hasNext()){
            String name = jsonReader.nextName();
            if ("name".equals(name)&&jsonReader.peek()!=JsonToken.NUMBER){
                person.setName(jsonReader.nextString());
            }else if("age".equals(name)){
                person.setAge(Integer.parseInt(jsonReader.nextString()));
            }else{
                //表示当所有都不成立的时候,就跳过该字段;解析下一个
                jsonReader.skipValue();
            }
        }
        jsonReader.endObject();
        return person;
    }
}
class Person{
    private String name;
    private int 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;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

json数据

[{"name":"花花","age":"10"},{"name":"哈哈","age":"10"}]

  

补充:

{"name":null}

while (jsonReader.hasNext()){
            String name = jsonReader.nextName();
            if ("name".equals(name)&&jsonReader.peek()!=JsonToken.NULL){
                person.setName(jsonReader.nextString());//表示如果name为空,就不设置值,此时默认情况下,就为空
            }else{
          //跳过该字段
          jsonReader.skipValue() 
       }
}

 

JsonReader.peek():看看值:没有真正的读取;(即光标没有移动)

JsonToken.STRING  :值是否为字符串

JsonToken.NUMBER:值是否为数字

jsonReader.nextString():读取字符串;

JsongReader.nextInt():读取int数据

jsonReader.nextDouble():读取数组:

 

使用GSON工具解析json数据为单个对象

将一个java对象转换为json字符串,或者将json字符串解析并创建java对象

注意:只能是一个对象;

import com.google.gson.Gson;

import java.io.*;

public class Demo {
    public static void main(String[] args) {
        Mygson();
    }

    private static void Mygson() {
        Gson gson = new Gson();
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("json\\person_json.json");
        InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
        Person person = gson.fromJson(inputStreamReader, Person.class);
        System.out.println(person);
    }
}
class Person{
    private String name;
    private int 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;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

json数据

{"name":"花花","age":10}

  

把一组JSON数据转换为java对象集合,或者把一个java对象集合转换为Json字符串

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        Mygson();
    }

    private static void Mygson() {
        Gson gson = new Gson();
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("json" +
                "\\person_json.json");
        InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
        TypeToken<List<Person>> listTypeToken = new TypeToken<List<Person>>() {
        };
        List<Person> list = gson.fromJson(inputStreamReader, listTypeToken.getType());
        System.out.println(list);
        System.out.println("---------------------------------------------------------");

        //将list对象转换json字符串
        String s = gson.toJson(list, listTypeToken.getType());
        System.out.println(s);
    }
}
class Person {
    private String name;
    private int 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;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

json数据

[{"name":"花花","age":"10"},{"name":"哈哈","age":"10"}]

  

 

MapperUtils

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MapperUtils {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     * 转换为 JSON 字符串
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static String obj2json(Object obj) throws Exception {
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * 转换为 JSON 字符串,忽略空值
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static String obj2jsonIgnoreNull(Object obj) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.writeValueAsString(obj);
    }

    /**
     * 转换为 JavaBean
     *
     * @param jsonString
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return objectMapper.readValue(jsonString, clazz);
    }

    /**
     * 字符串转换为 Map<String, Object>
     *
     * @param jsonString
     * @return
     * @throws Exception
     */
    public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(jsonString, Map.class);
    }

    /**
     * 字符串转换为 Map<String, T>
     */
    public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception {
        Map<String, Map<String, Object>> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() {
        });
        Map<String, T> result = new HashMap<String, T>();
        for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
            result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
        }
        return result;
    }

    /**
     * 深度转换 JSON 成 Map
     *
     * @param json
     * @return
     */
    public static Map<String, Object> json2mapDeeply(String json) throws Exception {
        return json2MapRecursion(json, objectMapper);
    }

    /**
     * 把 JSON 解析成 List,如果 List 内部的元素存在 jsonString,继续解析
     *
     * @param json
     * @param mapper 解析工具
     * @return
     * @throws Exception
     */
    private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
        if (json == null) {
            return null;
        }

        List<Object> list = mapper.readValue(json, List.class);

        for (Object obj : list) {
            if (obj != null && obj instanceof String) {
                String str = (String) obj;
                if (str.startsWith("[")) {
                    obj = json2ListRecursion(str, mapper);
                } else if (obj.toString().startsWith("{")) {
                    obj = json2MapRecursion(str, mapper);
                }
            }
        }

        return list;
    }

    /**
     * 把 JSON 解析成 Map,如果 Map 内部的 Value 存在 jsonString,继续解析
     *
     * @param json
     * @param mapper
     * @return
     * @throws Exception
     */
    private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception {
        if (json == null) {
            return null;
        }

        Map<String, Object> map = mapper.readValue(json, Map.class);

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object obj = entry.getValue();
            if (obj != null && obj instanceof String) {
                String str = ((String) obj);

                if (str.startsWith("[")) {
                    List<?> list = json2ListRecursion(str, mapper);
                    map.put(entry.getKey(), list);
                } else if (str.startsWith("{")) {
                    Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
                    map.put(entry.getKey(), mapRecursion);
                }
            }
        }

        return map;
    }

    /**
     * 将 JSON 数组转换为集合
     *
     * @param jsonArrayStr
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws Exception {
        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        List<T> list = (List<T>) objectMapper.readValue(jsonArrayStr, javaType);
        return list;
    }


    /**
     * 获取泛型的 Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 将 Map 转换为 JavaBean
     *
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T map2pojo(Map map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }

    /**
     * 将 Map 转换为 JSON
     *
     * @param map
     * @return
     */
    public static String mapToJson(Map map) {
        try {
            return objectMapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将 JSON 对象转换为 JavaBean
     *
     * @param obj
     * @param clazz
     * @return
     */
    public static <T> T obj2pojo(Object obj, Class<T> clazz) {
        return objectMapper.convertValue(obj, clazz);
    }
}

 使用

ObjectMapper instance = MapperUtils.getInstance(); 
JsonNode jsonNode = instance.readTree(data);  //封装的json字符串
JsonNode data1 = jsonNode.findPath("data");   //找到key为data的数据
String s = data1.toString();                  //data1转换为String
List<TbContent> tbContentDtos = MapperUtils.json2list(s, TbContent.class);  //json数据变成java对象

  

转载于:https://www.cnblogs.com/yanxiaoge/p/10772625.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值