I have some problem reading the "documentation" of schemaorg-java from google. What I'm trying to understand is how to deserialize "wrong" type of schema.org jsonld files.
I've found a site that use mainEntityOfPage in the wrong way by setting it to "true" instead of following schema.org's structure. I thought it's an old version of it, but I haven't found any versioning or citation about mainEnitityOfPage being boolean.
So my question: Is there a way to either deserialize the whole schema and skip the wrong properties or maybe a way to use this old format?
snippet:
<script type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "Recipe",
"mainEntityOfPage": true, [...]
Related
I want to serialize my java data classes to JSON. To be honest, I posted a relevant question few days ago, however I haven't got my answer so far. At the moment, all answers suggest the Jackson's annotations. But I prefer not to get the classes involved directly and I think it's better that delegate this work to views.
Nevertheless, I found out that SpringMVC supports GroovyTemplate and I've a pleasant experience to deal with Groovy templating and builders and so I've a good sense about them. But I could find Groovy templates to build only html files. All of the examples begin with similar lines like this:
html {
head {
title( ... )
...
}
}
Is there any way to write Groovy template in context of SpringMVC that provide JSON? For example, something like Grails JSON views known as gson files(see this).
I appreciate all for paying attention.
Groovy itself has good functionality to produce json.
Your classes can be easily converted into json:
import groovy.json.*
class SomeClass{
String name
int value
List someList = ['value1', 'value2', 'value3']
}
assert JsonOutput.toJson(new SomeClass(name:'myClass', value: 3)) ==
'{"value":3,"someList":["value1","value2","value3"],"name":"myClass"}'
it is also easy to create your own template engine.
For example:
def SOME_CLASS_TEMPLATE = {SomeClass someClass->
[
the_json:[
message: 'Message',
name: someClass.name,
first_list_value: someClass.someList?.getAt(0)
]
]
}
assert JsonOutput.toJson(SOME_CLASS_TEMPLATE(new SomeClass(name:'myClass', value: 3))) ==
'{"the_json":{"message":"Message","name":"myClass","first_list_value":"value1"}}'
formatted json output:
assert JsonOutput.prettyPrint(JsonOutput.toJson(SOME_CLASS_TEMPLATE(new SomeClass(name:'myClass', value: 3)))) ==
'''{
"the_json": {
"message": "Message",
"name": "myClass",
"first_list_value": "value1"
}
}'''
Also check other classes from groovy.json package (JsonGenerator, JsonBuilder) they may be more preferable for your tasks.
Since my very first days of Java + JSON I tried to extract just some certain parts of a JSON.
But no matter if which of the libraries I used:
Gson
json-simple
javax.json
it never was possible to make it quick and comfortable. Mostly for easy task or even prototyping. It already cost me many hours of different approaches.
Going trough the hierarchy of an JSON
Object jsonObject = gson.fromJson(output, Object.class);
JsonElement jsonTree = gson.toJsonTree(jsonObject);
JsonArray commitList = jsonTree.getAsJsonArray();
JsonElement firstElement = commitList.get(0);
JsonObject firstElementObj = firstElement.getAsJsonObject();
System.out.println(firstElementObj.get("sha"));
JsonElement fileList = firstElementObj.get("files");
This is dirty code for a reason. It shows how many early approaches looks like and how many people cannot achieve it to do it better early.
Deserializing JSON to a Java Object
Your have to analyse the complete JSON to create an complete Java-Object representation just to get access to some single memebers of it. This is a way I never wanted to do for prototyping
JSON is an easy format. But using libraries like that is quite difficult and often an problem for beginner. I've found several different answers via Google and even StackOverflow. But most were quite big larged which required to create a own specific class for the whole JSON-Object.
What is the best approach to make it more beginner-friendly?
or
What is the best beginner-friendly approach?
Using Jackson (which you tagged), you can use JsonPointer expressions to navigate through a tree object:
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper
.readTree("[ { \"sha\": \"foo\", \"files\": [ { \"sha\": \"bar\" }, { \"sha\": \"quux\" } ] } ]");
System.out.println(tree.at("/0/sha").asText());
for (JsonNode file : tree.at("/0/files")) {
System.out.println(file.get("sha").asText());
}
You could also use the ObjectMapper to convert just parts of a tree to your model objects, if you want to start using that:
for (JsonNode fileNode : tree.at("/0/files")) {
FileInfo fileInfo = mapper.convertValue(fileNode, FileInfo.class);
System.out.println(fileInfo.sha);
}
If your target class (FileInfo) specifies to ignore unknown properties (annotate target class with #JsonIgnoreProperties(ignoreUnknown = true) or disable DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES on the mapper), then you can simply declare the properties you are interested in.
"Best" is whatever works to get you going.
Generate Plain Old Java Objects from JSON or JSON-Schema
One little helper I found via my research was an Online-Tool like
http://www.jsonschema2pojo.org/
This is a little help, when you know about that. But the negative side I mentioned at point 2 is still there.
You can use JsonSurfer to selectively extract value or object from big json with streaming JsonPath processor.
JsonSurfer jsonSurfer = JsonSurfer.gson();
System.out.println(jsonSurfer.collectOne(json, "$[0].sha"));
System.out.println(jsonSurfer.collectOne(json, "$[0].files"));
I wonder do you now any program that can generate for me a Java code from transformation JSON to a XML? In Altova MapForce there is such a possibility, but unfortunately when I want use it, it returns me an Error:
Altova_Hierarchical_JSON.mfd: Mapping validation failed - 1 error(s), 0 warning(s)
Altova_Hierarchical: JSON components are not supported for Java.
The output component Altova_Hierarchical has no output file name set. A default file name will be used.
The second thing, that is important for me, is capabilities to create graphic mapping between JSON and XML like example below shows:
Thanks for the reply.
There is underscore-java library with static method U.xmlToJson(xml). I am the maintainer of the project.
<anyxml>data</anyxml>
Output:
{
"anyxml": "data",
"#omit-xml-declaration": "yes"
}
From a String like
<TestData Identifier=\"Test\" requiredAttribute=\"Present\"></TestData> <TestData Identifier=\"Test1\" requiredAttribute=\"Present1\"></TestData> <TestData Identifier=\"Test2\" requiredAttribute=\"Present2\"></TestData> <TestData Identifier=\"Test3\" requiredAttribute=\"Present3\"></TestData>
whats the best way to get the values of the attributes requiredAttribute i.e (Present,Present1,Present2...)
You can look into JAXB unmarshalling. Check out this page for more details, it should point to what you need
http://jaxb.java.net/tutorial/section_3_1-Unmarshalling-and-Using-the-Data.html#Unmarshalling and Using the Data
For basic XML parsing like this, I've found NanoXML # http://nanoxml.cyberelf.be/ to be about the easiest and mostlightweight.
Working with XML in Java send you down a long road to pain if you start using all the other libraries.
That's not XML - but you could do it with regex or by converting it to XML and parsing it out. The latter is probably more expensive. It depends on what the actual test data is and your requirements for it.
I am working on iphone application which contains HTTP Request and Response.
The format of the response is a key/value format compatible with the Java "Properties" stream format.
I want to store the response into a NSDictionay. Could you suggest me any way to do this?
Thank you.
sangee
Edit:
Thanks guyz for the quick replies!!!
is their any other ways to store them in NSSdictionay?
I just want to store the album name and description in an array like this:
mutablearray = [wrwr, dsf, my album];
could you please let me know if this possible or not?
Thanks again!!!
This is the response i got it for my HTTP request...
GR2PROTO
debug_album= debug_gallery_version= debug_user=admin debug_user_type=Gallery_User debug_user_already_logged_in= server_version=2.12 status=0 status_text=Login successful.
#GR2PROTO debug_album= debug_gallery_version= debug_user=admin debug_user_type=Gallery_User debug_user_already_logged_in=1
album.name.1=wrwr album.title.1=wrwr album.summary.1= album.parent.1=0 album.resize_size.1=640 album.thumb_size.1=100 album.perms.add.1=true album.perms.write.1=true album.perms.del_item.1=true album.perms.del_alb.1=true album.perms.create_sub.1=true album.info.extrafields.1=Description
album.name.2=dsf album.title.2=dsf album.summary.2= album.parent.2=0 album.resize_size.2=640 album.thumb_size.2=100 album.perms.add.2=true album.perms.write.2=true album.perms.del_item.2=true album.perms.del_alb.2=true album.perms.create_sub.2=true album.info.extrafields.2=Description
album.name.3=my album album.title.3=my album album.summary.3= album.parent.3=0 album.resize_size.3=640 album.thumb_size.3=100 album.perms.add.3=true album.perms.write.3=true album.perms.del_item.3=true album.perms.del_alb.3=true album.perms.create_sub.3=true album.info.extrafields.3=Description
If you can, I would recommend serializing the data as JSON (or XML, if you have to) and parsing it using TouchJSON or a similar parser. If you really can't, then you'll have to implement your own parser--take a look at NSScanner.
Look at NSStream and the Stream Programming Guide for Cocoa.
Back in the day when Java was fully integrated into Cocoa, NSStream mapped onto Java streams. It still might. IIRC, (it's been a while) NSStream will return a properly populated NSDictionary from a Java stream.
Edit:
It looks like the text returned is just a space delimited hash which is the Java version of dictionary. It takes the form of key=value space key=value. The only tricky part is that some of the hashes are nested.
The first line for example is nested:
debug_album{
debug_gallery_version{
debug_user=admin
debug_user_type=Gallery_User
debug_user_already_logged_in{
server_version=2.12
status=0
status_text=Login successful.
}
}
}
You need a recursive scanner to parse that. The "key=space" pattern indicates a nested dictionary.