Java接收json参数

 Java接收json参数

import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
 
@RestController
public class HelloController2 {
 
    /*
     * 第一种:以RequestParam接收
     * http://localhost:8080/test1?id=1
     * */
    @RequestMapping(value = "/test1",method=RequestMethod.GET)
    public void test1(@RequestParam("id") String id){
        System.out.println("id:"+id);    
    }
    
    /*
     * 第二种:以实体类接收
     * {"username": "zhangsan","id":"2"}
     * */
    @RequestMapping(value = "/test2",method=RequestMethod.POST)
    public void test1(@RequestBody User user) throws Exception{
        System.out.println("username:"+user.getUsername());    
    }
    
    /*
     * 第三种:以Map接收
     * {"username": "zhangsan","id":"2"}
     * */
    @RequestMapping(value = "/test3",method=RequestMethod.POST)
    public void test3(@RequestBody Map<String, String> map) throws Exception{
        System.out.println("username:"+map.get("username"));    
    }
    
    /*
     * 第四种:以List接收
     * [{"username": "zhangsan","id":"2"},{"username": "lisi","id":"1"}]
     * */
    @RequestMapping(value = "/test4",method=RequestMethod.POST)
    public void test4(@RequestBody List<User> list) throws Exception{
        for(User user:list){
            System.out.println("username:"+user.getUsername());
        }
    }
    
    /*
     * 第五种:以JSON对象接收
     * {"username": "zhangsan","id":"2","role":{"rolename":"admin"}}
     * */
    @RequestMapping(value = "/test5",method=RequestMethod.POST)
    public void test5(@RequestBody JSONObject json) throws Exception{
        System.out.println("username:"+json.getString("username"));    
        System.out.println("rolename:"+json.getJSONObject("role").getString("rolename"));
    }
}

### Java 接收并解析 JSON 数据Java 中,可以使用多种库来接收和解析 JSON 数据。以下是通过 `Gson` 和 `Jackson` 这两个常用库实现的示例。 #### 使用 Gson 库解析 JSON 数据 Gson 是 Google 提供的一个用于处理 JSON 的简单库。它能够轻松地将 JSON 转换为 Java 对象或将 Java 对象转换为 JSON 字符串。 ```java import com.google.gson.Gson; public class Main { public static void main(String[] args) { String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; // 创建 Gson 实例 Gson gson = new Gson(); // 定义与 JSON 结构匹配的类 class Person { String name; int age; String city; } // 将 JSON 字符串解析为 Java 对象 Person person = gson.fromJson(jsonString, Person.class); System.out.println("Name: " + person.name); System.out.println("Age: " + person.age); System.out.println("City: " + person.city); } } ``` 上述代码展示了如何利用 Gson 库将 JSON 字符串解析为自定义的 Java 对象[^1]。 --- #### 使用 Jackson 库解析 JSON 数据 Jackson 是另一个功能强大的 JSON 处理库,支持复杂的映射操作以及流式读写模式。 ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { String jsonString = "{\"name\":\"Jane\", \"age\":25, \"city\":\"Los Angeles\"}"; ObjectMapper objectMapper = new ObjectMapper(); // 定义与 JSON 结构匹配的类 class Person { String name; int age; String city; } // 将 JSON 字符串反序列化为 Java 对象 Person person = objectMapper.readValue(jsonString, Person.class); System.out.println("Name: " + person.name); System.out.println("Age: " + person.age); System.out.println("City: " + person.city); } } ``` 此代码片段说明了 Jackson 如何将 JSON 数据转化为 Java 对象。 --- #### 动态解析未知结构的 JSON 数据 当无法提前知道 JSON 数据的具体结构时,可以通过动态方法访问其字段。 ##### 使用 Gson 动态解析 ```java import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class Main { public static void main(String[] args) { String jsonString = "{\"key1\":\"value1\",\"key2\":{\"subKey\":\"subValue\"}}"; JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject(); System.out.println("Key1 Value: " + jsonObject.get("key1").getAsString()); System.out.println("SubKey Value: " + jsonObject.getAsJsonObject("key2").get("subKey").getAsString()); } } ``` 这段代码演示了如何用 Gson 来动态获取嵌套的 JSON 值[^3]。 ##### 使用 Jackson 动态解析 ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { String jsonString = "{\"key1\":\"value1\",\"key2\":{\"subKey\":\"subValue\"}}"; ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(jsonString); System.out.println("Key1 Value: " + rootNode.path("key1").asText()); System.out.println("SubKey Value: " + rootNode.path("key2").path("subKey").asText()); } } ``` 这里介绍了 Jackson 支持的动态节点遍历机制。 --- ### 总结 无论是静态还是动态场景下,都可以借助成熟的第三方库完成 JSON 数据的解析工作。对于已知固定格式的数据推荐采用对象绑定的方式;而对于不确定或者复杂多变的情况,则更适合运用树形模型进行逐层提取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开源字节

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值