I need to get the following information from an xml file:
"abridged_cast": [
{
"name": "Tom Hanks",
"characters": ["Woody"]
},
{
"name": "Tim Allen",
"characters": ["Buzz Lightyear"]
},
{
"name": "Joan Cusack",
"characters": ["Jessie the Cowgirl"]
},
{
"name": "Don Rickles",
"characters": ["Mr. Potato Head"]
},
{
"name": "Wallace Shawn",
"characters": ["Rex"]
}
],
So far I have been able to cut it to:
"abridged_cast": [
{
"name": "Tom Hanks",
"characters": ["Woody"]
The above is obtained using this regex:
\"abridged_cast\": \\[([^]]+)\\]
I need the regex to extend to the bottom ], but I can't seem to get it to work. I have tried a huge number of variations with no luck.
This is a bit of a train wreck, but:
"abridged_cast": \[(\s*\{\s*"name": "[a-zA-Z .]+",\s*"characters": \[("[a-zA-Z .]+", )*"[a-zA-Z .]+"\]\s*\}(,(?=\s*\{)|\s))*\s*\],?
See demo .
Since the "characters" field is an array, I've allowed for multiple terms there, an example of which I included in the demo.
Note that I have just shown the raw regex; to use it in java you'll have to escape the quotes and backslashes (which I didn't have the stomach for).
If you have complete and valid JSON, you can parse it with Jackson or GSON.
This is data classes:
public static class Role {
private String name;
private List<String> characters;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getCharacters() {
return characters;
}
public void setCharacters(List<String> characters) {
this.characters = characters;
}
}
public static class Cast {
@JsonProperty("abridged_cast")
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
And this is how you can parse it:
ObjectMapper om = new ObjectMapper();
Cast cast = om.readValue(s, Cast.class);
where s
is your JSON.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.