gpt4 book ai didi

java - 通过 JSON 解析器在 Java 中拆分和自定义字符串缓冲区?

转载 作者:行者123 更新时间:2023-12-02 11:20:14 26 4
gpt4 key购买 nike

我有一个字符串缓冲区(有效负载),如下所示:

"SQN":922,"Node_ID":"cc000000000000000000000000000002","Energy":"5.00","Power":"1.80","Sign":"6d226becaf5a5b..."

现在我想自定义它如下:

String part_1 = "{9 spaces}922{3 spaces}5.00{3 spaces}1.80"
String part_2 = "6d226becaf5a5b..."

执行此操作的最佳解决方案是什么?

我按照用户 Martin P 的建议尝试了这个:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.JSONArray.*;
import org.json.JSONException;
import org.json.JSONObject.*;
import org.json.JSONString;

String input = "{\"SQN\":922,\"Node_ID\":\"cc000000000000000000000000000002\",\"Energy\":\"5.00\",\"Power\":\"1.80\",\"Sign\":\"6d226becaf5a5b...\"}";

JSONParser obj = ((Object) new JSONParser().parse(input)).getAsJsonObject();
String sqnString = jsonObjectToString(obj, "SQN");
String energyString = jsonObjectToString(obj, "Energy");
String powerString = jsonObjectToString(obj, "Power");
String signString = jsonObjectToString(obj, "Sign");

StringBuilder sb = new StringBuilder();
sb.append("{whatever we need}").append(sqnString).append("{whatever we need}").append(energyString).append("{whatever we need}").append(powerString);
String part_1 = sb.toString();
String part_2 = signString;

System.out.println(part_1);
System.out.println(part_2);

但是,getAsJsonObject()jsonObjectToString(obj, "SQN") 未定义。

最佳答案

看起来你可以将它解析为 Json。

我使用 Gson 来做到这一点。这是maven的链接:Gson maven

请注意,我将您的字符串括在大括号 ( { } ) 中,以便稍后将其解析为 json

示例代码:

String input = "{\"SQN\":922,\"Node_ID\":\"cc000000000000000000000000000002\",\"Energy\":\"5.00\",\"Power\":\"1.80\",\"Sign\":\"6d226becaf5a5b...\"}";

JsonObject obj = new JsonParser().parse(input).getAsJsonObject();
String sqnString = jsonObjectToString(obj, "SQN");
String energyString = jsonObjectToString(obj, "Energy");
String powerString = jsonObjectToString(obj, "Power");
String signString = jsonObjectToString(obj, "Sign");

StringBuilder sb = new StringBuilder();
sb.append("{whatever you need}").append(sqnString).append("{whatever you need here}").append(energyString).append("{something else}").append(powerString);
String part_1 = sb.toString();
String part_2 = signString;

System.out.println(part_1);
System.out.println(part_2);
}

private static String jsonObjectToString(JsonObject obj, String name) {
return obj.getAsJsonPrimitive(name).getAsString();
}

结果输出:

{whatever you need}922{whatever you need here}5.00{something else}1.80

6d226becaf5a5b...

关于java - 通过 JSON 解析器在 Java 中拆分和自定义字符串缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979050/

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