Method of transforming complex JSON string into Java nested object

Qinshuiyu 2021-06-10 14:15:48
method transforming complex json string


background

In development , It is often necessary to integrate the more complex JSON The string is converted to the corresponding Java object . Record the solution here .

As shown below , It's intrusion detection JSON strand :

[{"rule_id":" rebound shell","format_output":" process pname Reverse connect to %dest_ip%:%dest_port%","info":{"process_events":{"pid":21,"pname":"nginx","cmdline":"curl www.cfda.com","ppid":7,"ppname":"bash"},"proc_trees":[{"pid":21,"pname":"nginx","cmdline":"curl www.cfda.com","ppid":7,"ppname":"bash"}],"containers":{"container_id":"fef4636d8403871c2e56e06e51d609554564adbbf8284dd914a0f61130558bdf","container_name":"nginx","image_id":"4eb8f7c43909449dbad801c50d9dccc7dc86631e54f28b1a4b13575729065be8","status":"Running"},"sockets":{"src_ip":"127.0.0.1","src_port":"8080","type":"1","in_out":"0","dest_ip":"localhost","dest_port":"80"}}}]

Method

First , According to this JSON String parses the corresponding data model AgentDetectEventData:


@Getter
@Setter
public class AgentDetectEventData {
@SerializedName("rule_id")
@JsonProperty("rule_id")
private String ruleId;
@SerializedName("format_output")
@JsonProperty("format_output")
private String formatOutput;
@SerializedName("info")
@JsonProperty("info")
private AgentDetectEventDetail info;
}
@Getter
@Setter
public class AgentDetectEventDetail {
@SerializedName("process_events")
@JsonProperty("process_events")
private ProcessEvent processEvent;
@SerializedName("proc_trees")
@JsonProperty("proc_trees")
private List<ProcessTree> procTree;
@SerializedName("containers")
@JsonProperty("containers")
private Container container;
@SerializedName("sockets")
@JsonProperty("sockets")
private Socket socket;
}
@Getter
@Setter
public class ProcessEvent {
@SerializedName("pid")
@JsonProperty("pid")
private String pid;
@SerializedName("pname")
@JsonProperty("pname")
private String pname;
@SerializedName("cmdline")
@JsonProperty("cmdline")
private String cmdline;
@SerializedName("ppid")
@JsonProperty("ppid")
private String ppid;
@SerializedName("ppname")
@JsonProperty("ppname")
private String ppname;
}
@Getter
@Setter
public class ProcessTree {
@SerializedName("pid")
@JsonProperty("pid")
private String pid;
@SerializedName("pname")
@JsonProperty("pname")
private String pname;
@SerializedName("cmdline")
@JsonProperty("cmdline")
private String cmdline;
@SerializedName("ppid")
@JsonProperty("ppid")
private String ppid;
@SerializedName("ppname")
@JsonProperty("ppname")
private String ppname;
}
@Getter
@Setter
public class Container {
@SerializedName("container_id")
@JsonProperty("container_id")
private String containerId;
@SerializedName("container_name")
@JsonProperty("container_name")
private String containerName;
@SerializedName("image_id")
@JsonProperty("image_id")
private String imageId;
@SerializedName("status")
@JsonProperty("status")
private String status;
}
@Getter
@Setter
public class Socket {
@SerializedName("src_ip")
@JsonProperty("src_ip")
private String srcIp;
@SerializedName("src_port")
@JsonProperty("src_port")
private String srcPort;
@SerializedName("type")
@JsonProperty("type")
private String type;
@SerializedName("in_out")
@JsonProperty("in_out")
private String inOut;
@SerializedName("dest_ip")
@JsonProperty("dest_ip")
private String destIp;
@SerializedName("dest_port")
@JsonProperty("dest_port")
private String destPort;
}

Here are two points of attention :

  • JSON The field names of strings are in the form of underscores , and Java Object property naming is hump style , There needs to be a transformation . Use Jackson Library , yes @JsonProperty annotation ; Use gson Library , yes @SerializedName annotation .

  • Need to add getter / setter Method .

After the object model is established , It's half done . Next , Is the use of json Library to parse .


Use jackson Library parsing

public class JsonUtil {
private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
// To maintain object version compatibility , Ignore unknown properties
MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// When serializing , skip null value
MAPPER.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// date Type conversion
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
MAPPER.setDateFormat(fmt);
}
/**
* Will a json The string is decoded to java object
*
* Be careful : If the string passed in is null, Then the returned object is also null
*
* @param json json character string
* @param cls object type
* @return The resolved java object
* @throws RuntimeException If analysis json There was an exception in the process
*/
public static <T> T toObject(String json, Class<T> cls) {
if (json == null) {
return null;
}
try {
return MAPPER.readValue(json, cls);
} catch (Exception e) {
return null;
}
}
public static <T> T jsonToObject(String src, Class<?> collectionClass,Class<?>... elementClasses){
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return MAPPER.readValue(src,javaType);
} catch (Exception e) {
logger.warn("Parse Json to Object error",e);
return null;
}
}
}

Single measurement :


public class JsonUtilTest {
@Test
public void testParseJson() {
try {
String json = RWTool.readFromSource("/json.txt");
List<AgentDetectEventData> ade = JsonUtil.jsonToObject(json, List.class, AgentDetectEventData.class);
Assert.assertNotNull(ade);
} catch (IOException e) {
e.printStackTrace();
}
}
}

introduce POM Rely on :


<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>

Use GSON analysis


public class GsonUtil {
static GsonBuilder gsonBuilder = null;
static {
gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
}
public static Gson getGson() {
return gsonBuilder.create();
}
public static <T> T fromJson(String json, Class<T> cls) {
return getGson().fromJson(json, cls);
}
public static <T> T fromJson(String json, Type type) {
return getGson().fromJson(json, type);
}
}

Single measurement :


public class GsonUtilTest {
@Test
public void testParseJson() {
try {
String json = RWTool.readFromSource("/json.txt");
List<AgentDetectEventData> ade = GsonUtil.fromJson(json, new TypeToken<List<AgentDetectEventData>>(){}.getType());
Assert.assertNotNull(ade);
} catch (IOException e) {
e.printStackTrace();
}
}
}

introduce POM by :


<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
版权声明
本文为[Qinshuiyu]所创,转载请带上原文链接,感谢
https://javamana.com/2021/05/20210522114904517o.html

  1. Spring MVC learning ten SSM environment construction (3) spring MVC file configuration
  2. Linux install sysstat, use iostat, mpstat, SAR, SA (Reprint)
  3. Explore the secrets of efficient jquery
  4. Java design pattern prototype pattern
  5. Summary of the sixth week of "Java programming" in 20165223
  6. Installation of MySQL under win7
  7. Knowledge point: process control of basic usage of MySQL
  8. Implementation of Java custom thread pool
  9. Spring MVC file download, upload, preview. Store in database in binary form (Reprint)
  10. Using netty to send and receive binary message
  11. Linux document processing command
  12. Oracle Client Language Problem
  13. Tomcat 7 user settings
  14. A problem caused by incomplete implementation of USB rndis network card driver on Linux host
  15. Paip. Spring gets the bean getBean without beanid
  16. Python data structure queue
  17. Find out the repeated numbers in the array
  18. Basic configuration of spring MVC series
  19. JAVA memory and GC
  20. Java Web Learning (24) -- common applications of filter
  21. Java back end learning route
  22. Regular automatic backup of MySQL database
  23. JQuery pictures loaded with scroll bar
  24. What should we know when learning MySQL?
  25. Java -- Analysis of container class library framework
  26. Spring type conversion (converter)
  27. Android Java abstract class
  28. The Maven project specifies the JDK version
  29. Wu Yuxiong's Python Oracle operation database (4)
  30. Oracle database exception handling and view
  31. Java reflection mechanism (2)
  32. be vigilant! MySQL becomes a new target for data blackmail
  33. Introduction to common SDK for API interface of open platforms
  34. Installing MySQL 5.7 under Linux
  35. Installation configuration and jreid test of redis3.2 under centos7
  36. Initialize the new HashMap & lt; String, String&gt;{ { put('str1':'abc');} }( (transfer)
  37. Hibernate learning notes 3.2 (hibernate build mapping)
  38. How to enable Arthas for spring boot project deployed in docker container
  39. Talking about equals and Java==
  40. Proxy mode of Java
  41. Mybatis framework (2)
  42. Basic usage of Linux nginx
  43. JQuery to add table rows, delete rows, call the date control
  44. About the workflow of mybatis and the comparison with JDBC and Hibernate
  45. JMeter HTTP get login
  46. Download and Install Apache Zookeeper on Ubuntu
  47. Java IO stream character stream FileReader, filewriter, copy of custom small array, BufferedReader, bufferedwriter, readline() and newline() methods, linenumberreader, use the specified code table to read and write characters
  48. Debugging errors encountered in Hadoop running
  49. The command of releasing memory in Linux
  50. Mybatis 3 source code analysis (3)
  51. Introduction of four switch types of rabbitmq
  52. JavaScript string (1) common functions
  53. Object oriented [day07]: introduction to class features (4)
  54. Linux DNS toolkit -- bind utils
  55. Oracle gets the first and last days of this week, this month, this quarter, and this year
  56. Install MySQL in Ubuntu
  57. Java implementation of sensitive word filtering (DFA algorithm)
  58. Image upload with spring MVC multipartfile
  59. Making Linux system installation disk under Ubuntu
  60. Introduction of Linux screen command