String、Map、JSONArray和JSONObject 之间的转化用法

String、Map、JSONArray和JSONObject 之间的转化用法

package com.tj.basic.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Test4 {
    public static void main(String[] args) throws IOException {

        String str = "[\n" +
                "  {\n" +
                "    \"userName\": \"张三\",\n" +
                "    \"province\": \"山西\",\n" +
                "    \"city\": \"威海\",\n" +
                "    \"phone\": \"17811111111\"\n" +
                "  },\n" +
                "  {\n" +
                "    \"userName\": \"李四\",\n" +
                "    \"province\": \"湖北\",\n" +
                "    \"city\": \"南通\",\n" +
                "    \"phone\": \"17311111111\"\n" +
                "  },\n" +
                "]";

        //String转JSONArray
        JSONArray jsonArray = JSONObject.parseArray(str);
        
        //String转JSONObject
        JSONObject jsons = JSONObject.parseObject(jsonArray.get(0).toString());

        //JSONObject转Map
        Map<String, Object> jsonsMap = new HashMap<>();

        for (Map.Entry<String, Object> entry : jsons.entrySet()) {
            jsonsMap.put(entry.getKey(), entry.getValue());
        }
        
        //Map转String
        String jsonsMapString = JSONUtils.toJSONString(jsonsMap);

        //OkHttp3 发送请求
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonsMapString);
        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/order/nowBuyOrder")
                .post(body)
                .addHeader("orgCode", "0000000001")
                .addHeader("Authorization", "Bearer aaaaaaaaaaaaaaaaaaa")//token
                .addHeader("url", "127.0.0.1")
                .addHeader("content-type", "application/json")
                .build();
        Response response = client.newCall(request).execute();

        //获取请求的返回体
        String string = Objects.requireNonNull(response.body()).string();
        JSONObject jsonObject = JSONObject.parseObject(string);
        System.out.println(jsonObject.get("message"));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值