我有一个字符串缓冲区(Payload),如下所示:
"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")
未定义。
答案 0 :(得分:1)
看起来你可以把它解析为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();
}
结果输出:
{无论你需要什么} 922 {无论你需要什么} 5.00 {其他} 1.80
... 6d226becaf5a5b