Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

java - is it possible to proccess JSON responses with the JDK or HttpComponents only?

we are upgrading our web app to use Facebook's Graph API, which returns JSON responses. However we don't want to add dependecy to a JSON library unless we have no other choice. For server-side http requests we use Apache HttpComponents.

Thus, my question is what are the classes (if any) in the JDK and/or in HttpComponents that I can use to process JSON responses? Code snippets are welcome :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately, native JSON support was delayed past Java 9.

But for the sake of sportmanship here is plain Java 8 hacky solution using Nashorn JavaScript engine without any external dependency:

String json = "{"foo":1, "bar":"baz"}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object o = engine.eval(String.format("JSON.parse('%s')", json));
Map<String, String> map = (Map<String, String>) o;
System.out.println(Arrays.toString(map.entrySet().toArray()));
// [foo=1, bar=baz]

Since Java 8u60 JSON.parse can be substituted with Java.asJSONCompatible which does better handling of JSON arrays.

Credits:

Effective way to pass JSON between java and javascript

https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...