java - 如何将String值转换为json?
问题描述
我有一串用逗号和“=”分隔的值。我需要将其转换为正确的 json 格式:
value = value.replace("=", ":");
String [] arrayStr=value.split(",");
JsonObjectBuilder builder = Json.createObjectBuilder();
String key = null;
for (String s: arrayStr){
if(key == null) {
key = s;
} else {
builder.add(key, s);
key = null;
}
}
JsonObject val = builder.build();
这是我拥有的内容以及我想如何对其进行调整:
[{Locale=en, Address={House=138, Street=Whitefield Road, CityDistrict=Bangalore, City=Bangalore, District=Bangalore, RegionCode=KA, Region=Whitefield, CountryCode=IND, Country=India, PostalCode=560066}}, {Locale=de, Address={House=138, Street=Whitefield Road, CityDistrict=Bangalore, City=Bangalore, District=Bangalore, RegionCode=KA, Region=Whitefield, CountryCode=IND, Country=India, PostalCode=560066}}]
[{"Locale":"en","Address":{"House":"138","Street":"Whitefield Road","CityDistrict":"Bangalore","City":"Bangalore","District":"Bangalore","RegionCode":"KA","Region":"Whitefield","CountryCode":"IND","Country":"India","PostalCode":"560066"}},{"Locale":"de","Address":{"House":"138","Street":"Whitefield Road","CityDistrict":"Bangalore","City":"Bangalore","District":"Bangalore","RegionCode":"KA","Region":"Whitefield","CountryCode":"IND","Country":"India","PostalCode":"560066"}}]
解决方案
String value = arrayObject.get(VALUE).toString();
JSONArray array = new JSONArray(value);
推荐阅读
- javascript - 正则表达式提取文本后跟括号(多合一字符串)
- css - 如何为 React tic-tac-toe 教程添加颜色?
- mongoose - 使用 Mongoose 按名称排序根,按位置排序它们的图像
- django - django def post 方法在 cbv 中不起作用
- apache-spark - spark-streaming-kafka 不适用于 scala-library
- terminal - 有没有办法在 Visual Studio Code 中更改树视图的位置?
- bash - 如何将变量设置为 cat 命令的输出?
- c++ - 使用 std::tuple_element<>::type 在折叠表达式中的另一个 type_traits 检查器中使用时被标记为始终为假
- json - 为什么我不能为变量分配在调试模式下可以看到的 JSON 值?
- json - 在不使用临时结构的情况下实现 Unmarshaller