开发者

Having String returned from String.split include partial of matching elements

final String json = "\"name\" : \"john\" , \"wo开发者_如何学JAVArth\" : \"123,456\"";    
String[] ss = json.split("\"\\s*,\\s*\"");
System.out.println(json);
for (String s : ss) {
    System.out.println("--> " + s);
}

The output is

"name" : "john" , "worth" : "123,456"
--> "name" : "john
--> worth" : "123,456"

Is there any way I can get

"name" : "john" , "worth" : "123,456"
--> "name" : "john"
--> "worth" : "123,456"


Using Regex

While I must agree that using a JSON parser makes a lot more sense, even if you want to use regex, String.split() is not the right tool. Use a Pattern and a Matcher:

final String json = "\"name\" : \"john\" , \"worth\" : \"123,456\"";
final Pattern pattern =
    Pattern.compile("\"(.*?)\"\\s*:\\s*\"(.*?)\"", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(json);
while(matcher.find()){
    System.out.println(matcher.group(1) + ":" + matcher.group(2));
}

Output:

name:john
worth:123,456

And if you really want to retrieve the quotes, change the pattern to

final Pattern pattern =
    Pattern.compile("(\".*?\")\\s*:\\s*(\".*?\")", Pattern.DOTALL);

Output:

"name":"john"
"worth":"123,456"

Of course this won't help with different JSON structures like nested object structures, arrays, primitives etc.


Using JSON parsers

But if your question is just about how to do this with JSON parsers, here is an example using JSONObject:

final String json = "{\"name\" : \"john\" , \"worth\" : \"123,456\"}";
final JSONObject jsonObject = new JSONObject(json);
@SuppressWarnings("unchecked")
final Iterator<String> it = jsonObject.keys();
while(it.hasNext()){
    final String nextKey = it.next();
    System.out.println(nextKey + ":" + jsonObject.getString(nextKey));
}

No classes needed. Output:

name:john
worth:123,456


This is a bit like parsing XML yourself. You can do it, but why bother? There are plenty of JSON parsers available. Use one of them to avoid reinventing the wheel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜