[英]Java - Reflection - How to get @RequestHeader value using reflection
[英]How to get particular Value by Key from JSON request by using Java Reflection
格式化的JSON数据
{
"userId":"123",
"userName":"user",
"age":12
}
从上述JSON请求中,我只想使用Java Reflection提取要存储在数据库中的userName
数据。
您可以使用jackson
json解析器。
下面只是一个代码示例(不能保证它将为您编译和工作),您应该将其放入接收请求的controler方法中。
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
您可以参考https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/package-summary.html了解api详细信息。
您可以使用以下代码从json数据中获取用户名。
JSONObject obj = new JSONObject(YOUR_JSON.toString());
String userName = obj.getString("userName");
有两种解决方案:
jackson
, gson
, json.org
...并从JsonNode获取用户名。 如果您只需要获取用户名,则可以使用正则表达式来检索它。
"userName":"((\\\\"|[^"])+)"
group(1)
是您的用户。
您可以使用JSON库解析字符串并检索值。
基本示例:
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);
}
}
输出:
UserName is: user
注意:不要忘记在POM文件中添加json依赖关系。
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
尽管有更多的JSON库可用,例如jackson , google-gson等等。 您可以使用其中任何一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.