How can I convert a given object (in a generic way with reflection) to pretty printable HTML?
What ready made library do you recommend that does this? I need support for simple nested objects (as long as they don't create loops in the object graph).
I tried to convert it to JSON, but DefaultPrettyPrinter is not HTML friendly.
You could create an XSLT style for the XML output of xstream on your object.
You could relatively easily write your own library for doing so. Here's some example code that you could modify relatively easily to show html. Another option is to display the JSON inside a code tag in html. One final option is to use ReflectionToStringBuilder in apache commons lang and again show the result inside of a code tag in html. Using apache commons is probably no better than the json format however.
Can be done in a two step process:
Convert object to JSON using any library of your preference, e.g. jackson:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Convert JSON string to HTML using a ready-made solution, such as json2html or write your own implementation. Have a look at the visualizer demo. You can also use the open-source jsoneditor which has an ad-supported online version.
Related
Is there already a CSON parser for Java? JSON is very difficult to hand-write (which I will be doing a lot of for this project) and I would rather not make my own CSON parser.
If not, is there another easy-to-use alternative to JSON that there is Java support for? The major reason I would like to avoid JSON is that I will be dealing with rather large multiline strings.
EDIT: I am referring to CoffeeScript Object Notation, not Cursive Script Object Notation.
YAML is supported by a ton of languages including Java and is very friendly with multiline strings.
I am trying to connect to a server which than connect to Google Places API and returns me my required data, the data that is being returned is in this format Here
Now in my Android Application i have this as a string or string[], issue is how can i now parse it as an XML or convert it to a native type like a List or something so i can than use it?
If you look at the returned string the actually array results starts after the two elemenets html_attributions & next_page_token so how can i seperate these and parse. Please help.
I would recommend you using the Gson library from Google, it can easily convert JSON -> Object . Here is a nice tutorial for you : tutorial.
This library is used by famous library Retrofit which is made for these calls and it will download the data and convert it to object using Gson : retrofit
There are a variety of ways to perform Json parsing in android.
If you only want to take the json and convert it to a java objects, then you can use gson. When serializing the object, gson will ignore any key in the json that doesn't match the java object that you are going to use for serialization. Therfore, just create your java object with the results instance variable,
https://code.google.com/p/google-gson/
You can use the built in JsonReader class to obtain the "results" and place that into a json array, if you want to single that out.
It is also good to become familiar with retrofit. This library provides a little more functionality than your solution needs however. This library abstracts the whole http request, response, json parsing and gson serializtion for you. So simply, you call a method on the object and get back the json in already serialized pojo.
http://square.github.io/retrofit/
If your returned data is in json format, create one JsonObject, Parse it as Json instead of xml, you can retrieve the value and create String[]. Take help from this tutorial
Of-course you can use Gson library to serialize and de-serialize jsonObject to pojoObject.
Ideally you should use a cool convenient library like Google GSON as mentioned by others for JSON parsing, but I'll explain how to use your json string with the old simple org.json library anyway. If your json string returned from server is in a string s, do:
JSONObject places=new JSONObject(s);
JSONArray results=places.getJSONArray("results");
for(int i=0;i<results.length();i++){
System.out.println(results.getJSONObject(i).getString("place_id"))
System.out.println(results.getJSONObject(i).getString("scope"));
}
It's a kind of odd question for an odd situation. I have a large JSON structure which I would like to represent in running groovy code. I need groovy objects that mirror the same structure as the JSON objects.
As to be expected a web search mostly returns results with groovy/json runtime conversion stuff, but nothing about things that output groovy code.
You might think this lazy but really it is a massive JSON structure! A converter would save days!
You can use Groovy's own JsonSlurper to parse JSON objects:
import groovy.json.*
def json = '{"name":"john", "surname":"doe", "languages": ["groovy", "python"]}'
def obj = new JsonSlurper().parseText(json)
assert obj.name == "john"
assert obj.surname == "doe"
assert obj.languages.containsAll("python", "groovy")
Of course the class is untyped: it's only known at runtime. If you want it to be typed, you can write a code which writes the code based on an example (since a json schema may be rare).
EDIT: if you want to generate the model classes code, you can try JSONGen, which "parses JSON to create client side source files to model the JSON data structure". I'm not aware of a solution for Groovy, but since java-groovy integrations is seamless, it shall work fine.
If you want a Groovy representation of your JSON, you can get that via the built-in JsonSlurper. This will give you Java Maps and Lists of data you can work with.
You can populate more specific, custom objects you've written to represent your JSON entities using the (3rd party) Jackson's data binding functionality (see this question as well).
Try using a JSON parser like this one. According to its documentation you just need to do
JSON.parse
to deserialize the data
My application allows users to define few templates for text etc. Eg: one of the shortcuts could be hi {{name}}, nice to meet you.
I have a complex json which has name and lot of inner jsons. I am looking for a good mustache kind of implementation in java which can replace the values of json into the string. Currently I am iterating through each key and replacing the string but I am looking for more elegant solution which gives the users more power in their templating like loops, conditions etc similar to mustache/handlebars.
Though mustache for java looks good, I haven't seen any implementation which can replace with a JSON. All examples applies on an object but not on a json object. Looks to me that internally, it uses an object mapper to convert an object to object and somehow it applies that.
Perhaps I can convert JSON into a map and provide it.
Probably I am missing something. Thanks.
You have to convert the JSON string to a Java object. You can use a nested Map, Multimap or create you own object to represent the structure.
You probably want to use a JSON-serializer to create a java object from the JSON-string. Good solutions are Jackson, Gson or Json-simple.
Once you have a correct Java representation of the JSON, you can use a template engine to do the string replacement. Known libraries are Freemarker, Velocity and StringTemplate
Personally I recommend Jackson+Freemarker, but all are good solutions.
Try Apache Velocity it does something very similar for property substitution in text.
Chunk is a very JSON-friendly template engine. Loops & conditions, tag syntax is similar to Mustache, and you can reference nested associative arrays of data fairly elegantly right from the template.
See sample code for JSON + Chunk in this answer.
I am trying to trying to get a value out of a json object. How would I get a third level json object:
json format looks like:
feedString = {"level1":[{"level2":{"level3":{"valueIWant":10}}}]}
Code is:
JSONObject jsonFeed = new JSONObject(feedString);
jsonFeed.get("level1.level2.level3.valueIWant");
Can I get nested levels in one get? What should my key look like?
You could give JSONiJ (JSON in Java) a shot; it's a Java version of JSONPath and basically maps (a subset of) XPath syntax onto JSON objects.
Also, see this SO question for some other ideas; it looks like json-path has a Java version, and uses dot notation.
The other option is to build an EL bridge between JSONObjects and something like MVEL or OGNL, which would give you the more-familiar dot notation. (I thought there was an MVEL/JSON bridge, but can't find it now.)
You should use JSONPath. Check out this Java implementation http://code.google.com/p/json-path/
It's been a while now, but I have some good news. Just tried beanutils and it works like a charm!
Assuming you have the json converted to map: (any parser can do that)
private Map<String, Object> json;
All you need is:
PropertyUtils.getProperty(json, "level1.level2.level3.valueIWant")
Have fun :)