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"));
}
}