gpt4 book ai didi

java - 如何形成json对象

转载 作者:行者123 更新时间:2023-11-30 05:27:44 25 4
gpt4 key购买 nike

我想使用 JsonObect 和 JsonArray 转换以下 JSON,但无法执行此操作。

{
"query": {
"bool": {
"must": [
{
"match": {
"customer.partnerName": "Synapse"
}
},
{
"range": {
"customer.billing.chargeAmount": {
"gte": 1,
"lte": 100
}
}
}
],
"filter": [
{
"match": {
"customer.configId": 15
}
}
]
}
}
}

我尝试使用JsonObject但无法实现结果。

最佳答案

这只是将 json 字符串简单复制/粘贴到 AndroidStudio 中,它会自动分割字符串并添加转义斜杠.. 它看起来很糟糕,但你编写的语法完全没问题..

    String jsonString = " {\n" +
" \"query\": {\n" +
" \"bool\": {\n" +
" \"must\": [\n" +
" {\"match\": \n" +
" { \"customer.partnerName\": \"Synapse\" }},\n" +
"\n" +
" {\n" +
"\"range\" : \n" +
"{\n" +
" \"customer.billing.chargeAmount\" : {\n" +
" \"gte\" : 1,\n" +
" \"lte\" : 100\n" +
" }\n" +
" }}\n" +
" ],\n" +
" \"filter\": [\n" +
" { \"match\": { \"customer.configId\": 15 }}\n" +
" ]\n" +
" }\n" +
" }\n" +
" }";

// HERE BEAUTIFIED
/*jsonString = "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"customer.partnerName\":\"Synapse\"}},{\"range\":{\"customer.billing.chargeAmount\":{\"gte\":1,\"lte\":100}}}],\"filter\":[{\"match\":{\"customer.configId\":15}}]}}}";
*/

try {
JSONObject object = new JSONObject(jsonString);

// NO ERRORS, OBJECT CREATED IN MY CASE
} catch (JSONException e) {
e.printStackTrace();
}

您拥有的第二个选项是以编程方式创建对象、内部对象和数组..就像这样..

    try {

JSONObject jsonObject = new JSONObject();


JSONObject query = new JSONObject();
jsonObject.put("query", query);


JSONObject bool = new JSONObject();
query.put("bool", bool);


JSONArray must = new JSONArray();
bool.put("must", must);


JSONObject matchWrap = new JSONObject();

JSONObject match = new JSONObject();
match.put("customer.partnerName", "Synapse");

matchWrap.put("match", match);

must.put(matchWrap);


JSONObject rangeWrap = new JSONObject();

JSONObject range = new JSONObject();

JSONObject customerBillingChargeAmount = new JSONObject();
customerBillingChargeAmount.put("gte", 1);
customerBillingChargeAmount.put("lte", 100);

range.put("customer.billing.chargeAmount", customerBillingChargeAmount);

rangeWrap.put("range", range);


must.put(rangeWrap);




JSONArray filter = new JSONArray();
bool.put("filter", filter);


JSONObject match2Wrap = new JSONObject();

JSONObject match2 = new JSONObject();
match2.put("customer.configId", 15);

match2Wrap.put("match", match2);


filter.put(match2Wrap);



String jsonString2 = jsonObject.toString();

// HERE THE SAME JSON STRING AS YOUR INPUT

} catch (JSONException e) {
e.printStackTrace();
}

当删除空格、制表符、换行符等时,这会产生与输入字符串相同的结果。

关于java - 如何形成json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58213255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com