-2
[{
  "field1": "",
  "field2": "I got you",
  "field3": [],
  "field4": ""
}]

My objective is to read only the field2 value. How can I do it using regex in java?

2
  • 4
    Note that JSON is not a regular language and thus regular expressions aren't a good or safe fit. You could use it but unless you really know what the value of field2 can be you'll eventually run into problems and even a very complex expression might not always do what you want. Better use a proper parser and extract the value (e.g. use Jackson's ObjectMapper.readTree(json) to get a generic representation of your JSON). Commented Mar 19, 2021 at 8:06
  • Why not use a library that reads it for you? Commented Mar 19, 2021 at 9:58

2 Answers 2

2

While it's certainly possible to treat JSON as any regular String, I'd say it's a better idea to extract the value using JSONPath. For your example it would look like this:

String json = ...;
String value2 = JsonPath.read(json, "$[0].field2");

The dollar sign stands for the root element, [0] is the first element of the array and field2 the name of the field you want to extract.

Sign up to request clarification or add additional context in comments.

Comments

0

I think it's duplicate of this question.

You can see this article for example if you realy want to use Regex.

But as Thomas says (in first comment to your post), better solution will be use json parser, examples you can see in this article.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.