Java uses rhino / nashorn to replace the third-party JSON conversion library

Java itself has its own JS engine. It has been supported since Java 1.6, and it is getting better and better. I am familiar with JS, so I have a bold idea. Why not bring my own JS engine for JSON conversion? In this way, we can avoid introducing other third-party libraries.

Background: Java 6 provides support for executing scripting language. This support comes from jsr223 specification, and the corresponding package is javax script。 By default, Java 6 only supports JavaScript scripts. Its underlying implementation is Mozilla rhino, which is a pure Java JavaScript implementation.

Except that openjdk does not have its own JS engine, sun / Oracle supports it. So you can do that.

I did it myself a long time ago. It's just that the performance of rhino in the early 1.6 / 1.7 is low, but it can't be compared with that in 1.8, because it has been upgraded to nashorn engine, a very fast JS engine. On the other hand, the code written before is very cumbersome. Although it has been refactored several times, it still can't be written well. So now I want to change it into a slightly "bright" version. Please see the following code, which is used to convert JSON strings into Java maps or lists.

In fact, it is very convenient to use! JS object itself is a map structure, while rhino native object nativeobject is the corresponding object of JS object in Java language. It has implemented the map interface, so nativeobject can be used as a map! Type conversion is OK! Eval () returns an object. If you can judge that the object type is nativeobject, you can directly convert (map) the object -- then use get and other methods, even in JSP pages.

The same is true of the list.

The following is the single test code.

It is worth noting that although jsengine provides a map interface, it usually can only read operations, if you execute map The operation of put (key, value) will cause the exception of unsupportoperation.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>