Formatted JSON Data
{
"userId":"123",
"userName":"user",
"age":12
}
From Above JSON request I want to fetch only userName
data to store in database by using Java Reflection.
Formatted JSON Data
{
"userId":"123",
"userName":"user",
"age":12
}
From Above JSON request I want to fetch only userName
data to store in database by using Java Reflection.
You can use a JSON library to parse the string and retrieve the value.
Basic Example:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{ \"userId\":\"123\", \"userName\":\"user\", \"age\":12 }";
JSONObject jsonObject = new JSONObject(jsonString);
String userName = jsonObject.getString("userName");
System.out.println("UserName is: " + userName);
}
}
Output:
UserName is: user
Note: Don't forget to add json dependency in POM file.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
Although more JSON libraries are available such as jackson, google-gson and many more. You can use any of them.
You can use the jackson
json parser.
Below is just a code sample(no guarantee that it will compile and work for you) you should put into your controler method receiving the request.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
//put below codes in your request handling method
String jsonStr = req.getReader().lines().collect(Collectors.joining(
System.lineSeparator()));
System.out.println(jsonStr);
JsonNode rootNode = new ObjectMapper().readTree(new StringReader(jsonStr));
JsonNode userName=rootNode.get("userName");
String userNameStr=userName.asText();
// store in data base
You can refer to https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/package-summary.html for api details.
You can use below code to obtain username from your json data.
JSONObject obj = new JSONObject(YOUR_JSON.toString());
String userName = obj.getString("userName");
There are 2 solutions:
jackson
, gson
, json.org
... And get username from JsonNode.If your requirement is just get Username, you can use regex to retrieve it
"userName":"((\\"|[^"])+)"
group(1)
is your user.