com.jayway.jsonpath.DocumentContext to org.json.JSONObject? - java

I want to both validate JSON and then use json-path for JPath queries. The validation is using json-schema which wants a JSONObject of the JSON to validate it. json-path wants a String or InputStream (code is in Java).
In a perfect world both could work off the same object as it's read in. However json-schema is built around the JSONObject and changing that would be a major re-write. And so, the next best is parse using json-path and then from the DocumentContext get a JSONObject of it.
Is there a way to do this? If not, then is the best way to read in the JSON as a JSONObject, feed that to the schema validation, and then get the String representation of that to pass to json-path?

Related

java objectmapper readvalue reading wrong string

I need to convert a certain JSON string to a Java object. I am using Jackson ObjectMapper for reading the JSON. The JSON String is something like this:-
"{"emailId":"gmail#rajnikant.com","accessToken":"accTok"}4".
When I am using objectMapper.readValue() for reading the JSON string to a specific destination class, it should throw an exception because of the JSON string being appended by 4. What should I do so that only valid JSON can be read and in other cases it will throw an exception?
To Jackson, GSON and others, a JSON string with some characters appended after the last } is valid JSON as long as what is contained between the {} is valid JSON.
As stated by a member of FasterXML (Jackson) team:
Yes. This is by design. If you want to catch such problems, you need to construct JsonParser, advance it manually. Existence of multiple root-level values is not considered a validity problem.
Reference: https://github.com/FasterXML/jackson-databind/issues/726
So if you need to enforce "clean" JSON you'll have to extend the default parser with your own functionality. However, IMO if it's OK to the default parser it should be OK to you too (unless we're dealing with some inter-language incompatibility scenario here).

Converting JSON Object(s) from file using Java

I have a JSON file with no clue on how data will be in it nor the structure of data.
The only thing known is that it will have either an array of JSON objects or a single JSON object.
I need to get each object from the file and store it as a separate item. In case of array of objects in the file, I should get an array of JSON strings which I can store in DB.
Basically, I need to read this file and separate out each JSON object from it and store it in DB as a string.
One of the ways to do it was to use JACKSON ObjectMapper and assign these items to a Hashmap as key value pairs, but I am not sure though how it can be done If there are list of JSON Objects in the file.
Sample JSON File:
[
{
"name":"Bob",
"type":"Email",
"from":"a#a.com",
"to":"b#B.com",
"attachments":[...],
.
.
.
}
]
Do you know the Object structure that the JSON has(let it be Array or a single one) ? If Yes,
First load the json string form the file into an in memory string.
check the string for Array existence, by searching for '[',']' in the outer structure of multiple occurrences of '{' or '}'
once you know whether you have an array or a single object, you can pass it as object reference to either Jackson or GSON parsers
create in memory Array of JsonObject.class say List. It is actually better to enclose this List inside another class. say myJsonObjects and have a List inside it.
Let us see GSON parsers (by google), though Jackson can also be used in the similar implementation
Gson gson = new Gson();
if(isArray){
myJsonObjects jsonArray = gson.fromJson(jsonStringFromFile,myJsonObjects );
}
else{
gson.fromJson(jsonStringFromFile,JsonObject);
}
http://google-gson.googlecode.com/svn-history/trunk/gson/docs/javadocs/com/google/gson/Gson.html
Jackson is my favorite JSON-to-POJO library. It doesn't really matter where you're loading the JSON from (a URL or from the filesystem), there are handlers for several input sources.
Here's an example:
Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);
As far as having an unknown number of JSON structures that you're about to parse, the first thing that comes to mind is to have a mapper for each type you're expecting. You could then wrap the parsing code in try/catch blocks so that if the first fails with whatever exception Jackson gives you when encountering an unexpected format, you can then try the next format and so on.
If you're just trying to generically parse JSON that you don't know the structure of beforehand, you can try something like this:
mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});
The documentation for Jackson is pretty good-- giving it a solid read-through should definitely help. Here's a good five minute tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
I prefer use Gson:
Gson gson;
Map<String, Object>parameters=gson.fromJson(myString);
the rest is iterate the map, i hope help you

Parsing JSON into a string array or xml

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"));
}

How do I print json structure for a multi-level json using java

I am very new to JSON and am not sure if the term "multi-level" json is correct. If not, please help correct it.
I have been tasked with printing the request and response structure of a given rest service. I have the api.json which refers to a host of json objects, which in turn refer to other json objects and so on...
Please note that I am interested in printing the structure and not the contents of the request and response.
I know that I can go ahead and do a recursive read of the files and get this done. But that does not seem right.
Can someone please provide some pointers for the same?
There is a general misconception about JSON. JSON is a format to represent a complex data structure as a string. That's it. JSON itself doesn't know anything about structure - it's really just a string. What you can do is parse the JSON string to get JavaScript objects (i.e. numbers, strings, arrays and things of type object).
This means that you can't really learn enough about the structure of the rest service by looking at JSON strings it accepts or sends. You need to look at the documentation or the internal objects which the service uses to parse the JSON instead.
Example:
{"foo":"bar"}
That tells you that the REST service accepts a JavaScript object and one of the possible parameters. But it doesn't tell you about the other 50 parameters.
If you only have the JSON, then you can use a parsing library to turn that into something that you can print. But unless you want pretty printing (indent and such), that's the same as printing the JSON string itself, so you don't gain anything.

What is the the best way to convert JSONObject to a domain object?

I have a rest service returning some data. I use Restlet client api as shown below to access this service. As you can see, it returns org.json.JSONObject. Is there a easy way to map this to the domain object (may be through annotations?) or should I have to write code to create the domain object?
Representation entity = new ClientResource(uri).get();
JSONObject json = new JsonRepresentation(entity).getJsonObject();
May be you can leverage from Gson library which has a function you need:
// Convert JSON into Java object
SomeObj obj = gson.fromJson(jsonObjStr, SomeObj.class)
You can read more here...
While there are decent APIs for easily mapping between Java data structures, e.g., from the JSONObject to your preferred data structure, since the incoming data format is JSON, I'd much prefer to just use a good JSON-to/from-Java API like Jackson. Depending on the preferred transformation details, the solution might be just one simple line of code with such an API.

Categories

Resources