How can I deserialize json object where in keys are present pointer? - java

I need to deserialize this json
{"dal.device.status":1,"dal.device.UID":"ZigBee:Yale Doorlock:ah.app.3781220503199452-1","service.bundleid":77,"dal.device.driver":"ZigBee","service.id":159,"service.scope":"singleton"}
But I don't how to do since there are pointers in key (e.g. "dal.device.status") I'm using google gson.
I'm able to deserialize this object using C# and Newtonsoft library using ClassAttributes. Is there something similar for java?

First question when seeing properties with dot in them in a json should be "god, oh god, why ? why all this hatred ?"
But if earth is at stake, you can simply deserialize this mess into an hashmap using gson and work from here.

Related

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

JAVA: json string to Map<string, string> (or an object)

I'm looking for a simple json library to convert json-string to Map or a POJO object. I know it's a duplicate, still I got specific requirements:
no weird dependencies like json-lib (why do you need all of them for a simple task?)
use few lines of codes to accomplish it (KISS principle).
I prefer conversion to Map but POJO will be good almost as well.
that's it.
what do you suggest?
Jackson is good, but I think you can also give GSON a try.
It's simple and easy to use. And there is a unit test for converting json string to Map and vice versa.
Check this:MapTest.java
Hope this help you.
Jackson would be best in this case.

Access nested json data in single get?

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 :)

Memcache Serializable JSONObject?

I'm using json.org JSONObject. I've tried to serialize it to memcache and got the not so cool java.io.NotSerializableException: org.json.JSONObject. Looking at the JSONObject code it seems that it's nothing more then a Map wrapped by JSON logic. Why not make it serializble then?
I would like to be able to store the object into memcache in an easy interface. Is there a similar API implementation of JSONObject that is also serializble. Alternatively, what memcache friendly serialization / deserialization technique do you use ?
Thank you,
Maxim.
JSONObjects are meant be sent as simple strings. So instead of storing the Java serialized form of your JSONObjects you should store the stringified forms.
if you use org.json.JSONObject, it doesn't implement the Serializable interface. For that reason it can't be serialized. Instead, you can put the String version of JSONObject into MemCache.
I have found http://code.google.com/p/json-simple/ to be API compatible implementation of org.json.JSONObject. It does not have all the getDouble, getLong, getJSONArray methods but other then that the concepts are pretty much the same.
It excels over org.json implementation by the fact that it simply extends HashMap for JSONObject and ArrayList for JSONArray making these objects by definition serializble and thus cacheable.

Categories

Resources