Java CSON parser? - java

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.

Related

Converter from Json into groovy CODE?

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

Mustache kind of String replacement in Java

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.

XML data types specification

While there is plenty of documentation about XML document structure, there are very few links to how non textual data (eg. integer and decimal numbers, boolean values) should be managed.
Is there a consolidated standard? Could tell me a good starting point?
POST SCRIPT
I add an example because the question is actually too generic.
I've defined a document structure:
<rectangle>
<width>12.45</width>
<height>23.34</heigth>
<rounded_corners>true</rounded_corners>
</rectangle>
Since I'm using DOM, the API is oriented to textual data. Say doc is an instance of Document. doc.createTextNode("takes a string"). That is: API doesn't force towards a particular rapresentation.
So two question arise:
1) saving bolean true as 'true' instead of uhm, 1/0 is a standard?
2) i have to define simple methods that write and parse from and to this string representations. Example. I may use java wrappers to do this conversion:
Float f = 23.34;
doc.createTextNode(f.toString());
but does it adhere to the xml standard for decimal numbers? If so, i can say that a non-java programs can read this data because the data representation is xml.
why not jaxb
This is just an example, my xml is made up of a big tree of data and i need to write and read just a little part of it, so JAXB seems not to fit very well. Binding architecture tends to establish a tight copuling between xml structure and class structure. Good implementations like moxy let you loosen this coupling, but there are cases in wich the two structures simply don't match. In those cases, the DTO used to adapt them would be more work than using DOM.
Of course, there are dozens of official standards related to core XML. Some of the important ones:
XML schema 1.1 overview
XML schema 1.1 - datatypes ('XSD')
XML schema 1.1 - structures
Core XML overview
XML 1.0
XML 1.1
Further specification like XPath, XQuery are available at www.w3.org/standards/xml/. As you tagged this question with java you may be interested in JAXB as well, which defines a standard approach for mapping XML to Java and vice versa.
You can leverage the javax.xml.bind.DatatypeConverter class to convert simple Java types to a String that conforms to the XML Schema specification:
Float f = 23.34f;
doc.createTextNode(DatatypeConverter.printFloat(f));

Convert any object to pretty HTML in java

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.

Java: Serializing String[] Array to store in a MySQL Database?

Yes, I know it's bad practice and I should instead normalize my tables. That put aside, is it possible to serialize a String [] array and store it in the database?
I am from the lenient and forgiving world of PHP, where invoking the serialize() function and would convert the array into a string.
Is there an equivalent of doing such heresy in Java?
Apart from normalization, are there more elegant ways of storing String Arrays in the database?
In case it's applicable, I am using the jdbc driver for my MySQL connections.
Yes. You can serialize any Java objects and store the serialized data into MySQL.
If you use the regular serialization (ObjectOutputStream), the output is always binary. Even String is serialized into binary data. So you have to Base64 encode the stream or use a binary column like BLOB.
This is different from PHP, whose serialize() converts everything into text.
You can also use the XML serialization in Java (XMLEncoder) but it's very verbose.
If you're thinking in terms of raw arrays, you're still writing PHP in Java.
Java's an object-oriented language. An array of Strings really isn't much of an abstraction.
You'll get perfectly good advice here telling you that it's possible to serialize that array of Strings into a BLOB that you can readily store in MySQL, and you can tell yourself that leniency is a virtue.
But I'll going to remind you that you're losing something by not thinking in terms of objects. They're really about abstraction and encapsulation and dealing with things at a higher level than bare metal ints, Strings, and arrays.
It'd be a good exercise to try and design an object that might encapsulate an array or another more sophisticated data structure of child objects that were more than Strings. There'd be a 1:m relationship between parent and child that would better reflect the problem you were really trying to solve. That would be a far more object-oriented design than the one you're proposing here.
There are various good serialization/deserialization libraries that automatically convert JavaBean objects to/from XML and JSON strings. One I've had good experience with is XStream.
Java's built-in support for serialization can do the same thing, and you can write custom serialization/deserialization methods for Java to call.
You can roll your own serialization methods too, eg converting to and from a comma-separated value (CSV) format.
I'd opt for a library like XStream first, assuming there's a very compelling reason not to normalize the data.
You don't want to serialize the array. I'm not sure why you'd serialize it in PHP either, because implode() and explode() would be more appropriate. You really should normalize your data, but aside from that, you could very easily Google a solution for converting an array to a string.
But surely the more logical thing to do would be to save each string as its own record with a suitable identifier. That would probably be less coding than serializing -- a simple loop through the elements of the array -- and would result in a clean database design, rather than some gooey mess.
If you really don't want to normalize this values into a separate table where each string would be in its own row, then just convert your array to a list of comma separated values (possibly escaping commas somehow). Maybe quoting each string so that "str1","str2".
Google for CSV RFC for spec on how this should be properly escaped.

Categories

Resources