Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills of parsing XML and JSON content

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the skills of parsing the content of XML and JSON. It is very detailed and has certain reference value. Friends who are interested must finish it!

An overview of some techniques for parsing the contents of XML and JSON

In the absence of a unified standard, when a system connects multiple external systems, it is often encountered that the request interface response data is heterogeneous. It is possible to return XML or return.

JSON . In addition to the different return types, the content structure is also different. Take the XML type as an example

API 1 returns the content

16112638767472747178067 OK 200...

API 2 returns the content

16112638767472747178068 succeeded 1.

If it is obviously unreasonable to deal with content in each format in our system, we only care about three kinds of information in the above content, namely, business ID, status value and description information, then whether we can abstract these three kinds of information

After obtaining this information, proceed with the business logic processing.

Parsing XML and JSON

According to the business abstraction, we need to get three kinds of information from XML or JSON content, which we will use XPath and JSONPath to parse here. For example, get the important information of interface 1.

We can set three XPath expressions

{bid: "/ root/bizKey", code: "/ root/returnCode", description: "/ root/returnMsg"}

Bid,code and description correspond to the field names defined by our system itself.

Parsing JSON content is the same, except that JSONPath expressions are defined.

Deal with the data content in two steps

Suppose we get the bid,code and description information from the original XML and JSON data

Obtained from interface 1

{bid: '16112638767472747178067, code:' 200, description: 'OK'}

Obtained from interface 2

{bid: '16112638767472747178068, code:' 1century, description: 'success'}

Suppose we know from the interface 1 document that the status value 200 indicates that the request was successful, and from the interface 2 document that the status value 1 indicates that the request was successful. Although they all indicate that the request was successful, we still cannot

Save them as they are in our business-related tables (of course, these response data still need to be saved in another record table, at least to facilitate troubleshooting).

Suppose our business-related table is designed like this.

Field name type description bidstring business IDcodeint status value, 0 = initial, 1 = request, 2 = success, 3 = failed descriptionstring description

Therefore, we must also define rules to convert the status value 200 returned by interface 1 to 2 of our system, and the state value 1 returned by interface 2 to 2 of our system.

To sum up, parse the XML and JSON data content in two steps

Parsing to get important information according to XPath or JSONPath expression

Convert the state value according to the rule

The first step is to parse the data to get important information.

Take XML as an example

Public class XmlParseUtils {private DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance (); private XPathFactory xpathFactory = XPathFactory.newInstance (); / * * @ param param data content * @ param paths expression * @ return * @ throws Exception * / public Map parse (String param, Map paths) throws Exception {InputSource inputSource = new InputSource (new StringReader (param)); Document document = dbFactory.newDocumentBuilder () .parse (inputSource) Map map = Maps.newHashMap (); for (String key: paths.keySet ()) {XPath xpath = xpathFactory.newXPath (); Node node = (Node) xpath.evaluate (paths.get (key), document, XPathConstants.NODE); if (node = = null) {throw new Exception ("node not found, xpath is" + paths.get (key)) } map.put (key, node.getTextContent ());} return map;}}

The return type of the parse function can also be Map, using Map for the time being.

The second step is to change the state value according to the rule.

This step is a little bit troublesome, but let's not think about the code implementation, anyway, you can think of someone else may have done it for you. First of all, we define the rules according to the interface document and write the rule expression (or something else).

Expressions again. Assuming that the returned status value of interface 1 is relatively simple, with only 200 indicating success and failure in other cases, we can define the rule as follows

Code.equals? 2: 3

Or

twenty-three

Or

Function handle (arg) {if (arg = = 200) {return 2;} return 3;} handle (${code})

The above defines three different types of state value transition rules based on the same document, which must require three different implementations. The following are explained one by one

Trinomial expression

Code.equals? 2: 3 is a trinomial expression, we will use the jexl engine to parse, using the first step to parse the data to get the results of important information, we can do this

Public Object evaluateByJexl (String expression, Map context) {JexlEngine jexl = new JexlBuilder () .create (); JexlExpression e = jexl.create_Expression (expression); JexlContext jc = new MapContext (context); return e.evaluate (jc);} FreeMarker template 23

Deal with this template. We can do this.

/ * @ param param FreeMarker template * @ param context * @ return * @ throws Exception * / public String render (String param, Map context) throws Exception {Configuration cfg = new Configuration (); StringTemplateLoader stringLoader = new StringTemplateLoader (); stringLoader.putTemplate ("myTemplate", param); cfg.setTemplateLoader (stringLoader); Template template = cfg.getTemplate ("myTemplate", "utf-8") StringWriter writer = new StringWriter (); template.process (context, writer); return writer.toString ();}

If the FreeMarker template is complex and precompiling from the template to Template may consume more performance, consider caching Template.

JavaScript snippet function handle (arg) {if (arg = = 200) {return 2;} return 3;} handle (${code})

There is ${code} in this js code, which first needs to use FreeMarker rendering to get the call parameters of the real handle method, and then

Public Object evaluate (String expression) throws Exception {ScriptEngineManager manager = new ScriptEngineManager (); ScriptEngine engine = manager.getEngineByName ("javascript"); return engine.eval (expression);}

The performance of ScriptEngineManager is not very optimistic, after all, it is a language engine.

Advantages and disadvantages of comparison type implementation with different conversion rules Jexl simple expression (easy) simple (simple) FreeMarker template FreeMarker----JavaScript code snippet FreeMarker + ScriptEngine intuitive process is complex, performance problems

It seems that Freemarker is a good choice.

So far, the two-step tips have been implemented, both using ready-made code implementation.

Maybe we will have the challenge of knowing the current business state value of the system when we do the state value transition.

At this point, the Freemarker expression might look like this

two hundred and twenty three

Here we can use the features of Freemarker to customize Java functions or utility classes, which can be called in the template.

The above is all the content of this article entitled "what are the skills for parsing XML and JSON content?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report