Java解析json数组三种情况

本文详细介绍如何使用阿里巴巴FastJSON库解析不同类型的JSON数据,包括简单对象、数组及复杂嵌套对象,通过实例演示如何将JSON字符串转换为Java对象,如Map、List、自定义JavaBean等。
package com.example.demo.json;


import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.demo.common.Person;


public class JsonLib {
	//json字符串-简单对象型
	private static final String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
	//json字符串-数组类型
	private static final String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
	//复杂格式json字符串
	private static final String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
	@SuppressWarnings("unchecked")
   public static void main(String[] args) {
       //demoJson();
		
		//testJSONStrToJSONObject();//json字符串转化对象
		//testJSONStrToJSONArray();//json数组转化json对象
		testComplexJSONStrToJSONObject();//json对象嵌套json对象
   }
	
	/**
     * 复杂json格式字符串与JSONObject之间的转换
     */
    public static void testComplexJSONStrToJSONObject(){
    	System.out.println(COMPLEX_JSON_STR);
        JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
        //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON,所以这样也是可以的
        System.out.println(jsonObject);
        String teacherName = jsonObject.getString("teacherName");
        Integer teacherAge = jsonObject.getInteger("teacherAge");
        JSONObject course = jsonObject.getJSONObject("course");
        JSONArray students = jsonObject.getJSONArray("students");
        System.out.println(teacherName+"------"+teacherAge+"===json对象===="+course+"----json数组----"+students);
        JSONArray jsonArray = JSON.parseArray(students.toString());
        System.out.println(jsonArray);
    }
	
	/**
     * json字符串-数组类型与JSONArray之间的转换
     */
    public static void testJSONStrToJSONArray(){

        JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
        //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的

        //遍历方式1
        int size = jsonArray.size();
        for (int i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
        }

        //遍历方式2
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
        }
    }
	
	/**
     * json字符串-简单对象型与JSONObject之间的转换
     */
    public static void testJSONStrToJSONObject(){

        JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
        //JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的

        System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));

    }
	public static void demoJson() {
		/**
		    * 将 Json 形式的字符串转换为 Map
		    */
		   String str = "{\"name\":\"Tom\",\"age\":90}";
		   JSONObject jsonObject = JSONObject.parseObject(str);
		   Map<String, String> params = JSONObject.parseObject(jsonObject.toString(), new TypeReference<Map<String, String>>(){});
		   System.out.println(params);

		   /**
		    * 将 Json 形式的字符串转换为 JavaBean
		    */
			 str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
			 jsonObject = JSONObject.parseObject(str);
			 System.out.println(jsonObject);
			 Person person = JSON.parseObject(str, new TypeReference<Person>() {});
			 System.out.println(person.toString());
	}
}

 

### 解析 JSON 数组Java 中的方法 #### 使用 Jackson 库解析 JSON 数组 Jackson 是一种流行的用于处理 JSON 数据的 Java 库。通过 `ObjectMapper` 类可以轻松读取并转换 JSON 数组Java 对象列表。 ```java import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; public class JsonArrayExample { public static void main(String[] args) throws IOException { String jsonArrayString = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":25}]"; ObjectMapper objectMapper = new ObjectMapper(); List<Person> personList = objectMapper.readValue(jsonArrayString, objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class)); for (Person p : personList){ System.out.println(p); } } private static class Person{ private String name; private int age; @Override public String toString(){ return "Name: "+this.name+", Age:"+this.age; } } } ``` 此代码片段展示了如何利用 Jackson 的 `readValue()` 方法来解析 JSON 字符串表示形式中的数组,并将其映射为指定类型的对象集合[^1]。 #### 使用 Gson 库解析 JSON 数阵 Gson 提供了一种简单的方式来序列化和反序列化 Java 对象与 JSON 表达式之间的关系。对于 JSON 数组来说,可以通过创建一个泛型类型实例来进行解析操作: ```java import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class GsonJsonArrayExample { public static void main(String[] args) { String jsonString = "[{'name':'Tom','age':28}, {'name':'Jerry', 'age' : 27}]"; Type listType = new TypeToken<ArrayList<Person>>(){}.getType(); Gson gson = new Gson(); List<Person> persons = gson.fromJson(jsonString, listType); for(Person person : persons){ System.out.println(person.getName()); } } private static class Person { private String name; private Integer age; // Getters & Setters... public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } } ``` 这段程序说明了怎样借助于 Google 的 Gson 工具包实现相同的功能——即把 JSON 文本转化为相应的 Java 实体类列表[^2]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值