我有两个字符串如下:
- “activityTypes”:{“activityType”:“COLLECTIONS”},
- “activityTypes”:{“activityType”:“E-DROP”},
我需要将其转换为 -
- “activityTypes”:[{“activityType”:“COLLECTIONS”}],
- “activityTypes”:[{“activityType”:“E-DROP”}],
上述转换中java的正则表达式是什么?
答案 0 :(得分:0)
您可以使用REGEX或处理JSON来获得预期的输出。
假设您要使用Mongodb-java-driver-3.0.1将此代码用于Mongodb
BasicDBObject myobj = new BasicDBObject();
BasicDBObject myobj1 = new BasicDBObject().append("activityType", "COLLECTIONS");
myobj.append("activityTypes", myobj1);
System.out.println(myobj);
List<BasicDBObject> myarray = new ArrayList<>();
myarray.add(myobj1);
myobj.put("activityTypes", myarray);
System.out.println(myobj);
这将输出为
{ "activityTypes" : { "activityType" : "COLLECTIONS"}}
{ "activityTypes" : [ { "activityType" : "COLLECTIONS"}]}
答案 1 :(得分:0)
可能有更好的方法。
public static void main(String[] args) {
// TODO code application logic here
String string1 = "\"activityTypes\": {\"activityType\": \"COLLECTIONS\"} "
+ "\n \"activityTypes\": {\"activityType\": \"E-DROP\"},";
Scanner input = new Scanner(string1);
Pattern pattern = Pattern.compile("\\\"activityTypes\\\": \\{[\\s\\S]+?\\}");
while(input.hasNext())
{
Matcher m = pattern.matcher(input.nextLine());
if(m.find())
{
string1 = m.group().replace("{", "{[");
System.out.println(string1);
}
else
{
System.out.println("Nothing found!");
}
}
input = new Scanner(string1);
pattern = Pattern.compile("\\\"activityTypes\\\": \\{\\[[\\s\\S]+?\\}");
while(input.hasNext())
{
Matcher m = pattern.matcher(input.nextLine());
if(m.find())
{
string1 = m.group().replace("}", "]}");
System.out.println(string1);
}
else
{
System.out.println("Nothing found!");
}
}
}