converting a complex json object to java object through gson - java

I've a problem with storing a Json object as a java object, I'm not sure what structure to use to store something like this:
'tags':[{'CouchDB':1},{'JSON':1},{'database':1},{'NoSQL':1},{'document_database':1}]
I have tried 2 dimensional arrays, ArrayLists and Hashtables but didn't work, could be down to my poor implementation or I just have it wrong, need help with this ASAP please!
I'm using GSON to convert from the Json String to the Java object, and have other parts working fine, the problem is just having GSON parse this structure properly

Try using http://jsonlint.com/ to make sure that your JSON is valid (it doesn't seem to be)
If you change your tags to {"name":"couchdb"}, your Java class could look like this:
public class Tag
{
private String name;
...
}
And your container class could have a private List<Tag> tags;

Seems, like your tags are just a bunch of keys with a count (or something along those lines) attached to each one, i.e. key-value pairs which is just a hashtable e.g.:
{'tags':{'CouchDB':1,'JSON':1,'database':1,'NoSQL':1,'document_database':1}}
You should be able to convert the above without any trouble, if you can't I would say you have some sort of configuration issue as opposed to any kind of problem with the format of the data.

Related

Gson cannot deserialize same string it created?

I have a HashMap<Picture, String> with Picture being a data-class I created in kotlin. I save the HashMap into the SharedPreferences using gson.toJson(hashmap) and this works fine. But when I try to deserialize the very same string (I checked) into the HashMap<Picture, String> again, it fails with a weird error.
This is the Exception:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $.
This is the string for reference:
{
"Picture(image_url\u003dhttps://nftmintapp.infura-ipfs.io/ipfs/QmZnbgRFCvqXeahD37vaRANjPiyF9oCC2aWw1TwHat8SaU, creator_name\u003dmarkus, creator_address\u003d0x0, image_name\u003dethOS3, additional_url\u003dhttps://google.com)":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
The String I save in reference to the String is a Bytearray that I convert to string using Base64.encodeToString(bytes, Base64.NO_WRAP).
I assumed that gson would be able to de-serialize anything it serialized itself, has anybody ever encountered this?
The JSON specification only allows strings as property names of JSON objects. Gson works around this by simply calling the toString() function on Map keys and serializing that as JSON property names. However, for deserialization it uses the standard JSON deserialization logic.
For simple Map keys such as String or Int this works just fine, but for complex key types, such as the Picture class in your case, this leads to undesired behavior.
The solution is to either
restructure your code so it uses a Map<String, ...> and for example stores the picture data as part of the Picture class as well, or have a data class which contains the picture data and the Picture object
or to
use GsonBuilder.enableComplexMapKeySerialization(), see also the user guide for additional information
In case you already have released a version of your app with this faulty JSON serialization logic and you want to preserve backward compatibility, you will have to write a JsonDeserializer (or TypeAdapterFactory, but that is a bit more complicated) which tries to deserialize this faulty JSON value.

Parsing JSON string and preserving key-data order when using json-simple without manually constructing HashMap

I know that this topic has been talked about, and the use of a LinkedHashMap is a 'hacky' way to maneuver this, but if I'm given thousands of JSON strings as input, and eventually want to output them back in their original form, is there anyway to preserve the order without manually constructing LinkedHashMaps.
For example a string like this
{"key":1,"surname":"Reed","given":"Ryan","address":{"state":"CA","postal":"90210"},"gender":"M"}
Right now if I parse the object like so:
JSONObject jsonObject = (JSONObject) parser.parse(str);
System.out.println(jsonObject);
My output will look like this:
{"surname":"Reed","gender":M,"address":{"postalCode":"90210","state":"CA"},"key":1,"given":"Ryan"}
Is there anyway I can get the output to match exactly like the given input?
In Json property structure, order does not matter. but if you have specific order in your mind you can use Jackson to order them in you desirable way, both in your server and client apps.
https://www.baeldung.com/jackson
http://www.davismol.net/2016/10/24/jackson-json-using-jsonpropertyorder-annotation-to-define-properties-serialization-order/
I think it is impossible by default.
You can refer to this RFC https://www.ietf.org/rfc/rfc4627.txt
An array is an ordered sequence of zero or more values.
If you want to hack it you can override the data structure and use the data structure which preserves the order.

List of tuples in Android?

I do not find possibility of "list of tuples" in Java. What alternative structure do you suggest where can be stored in a list / array?
In other languages like in Swift, declaring it looks like this:
var items: [(id: String, text: String, totalMatch: Int16)] = [];
I would avoid declaring a class, fields.
SQL
I don't know what you really want to do. But if you want to manage Data you could use a sql liste Database provided per dafault by android.
Your Objects would be stored very lightweight but you have to give a lot of effort.
Class/ArrayList
Otherwise just use a ArrayList. Until you dont have more than 10000 Items its no Problem even on older Devices.
You will need two classes.
class Item{
String id;
String text;
int totalMatch;
}
class YourClass{
ArrayList<Item> items = new ArrayList<Item>();
}
JSON Parser
Very good and easy parser for JSON Files is GSON from Google: See:
https://github.com/google/gson
Old question but if anyone still in need of, possibly you can try Pair class from android.util package inside List. Something like this:
List<Pair<String, Integer>> myPairList = new ArrayList<>();

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 complex string of JSON in java

I want to parse a JSON string which is quite complex. It has somewhat following format
{ A:{ list of around 20 objects},B:1}
These objects inside A again contains some other objects or the datatypes supported by JSON. I have checked couple of examples and documentations.
I found this example to be helpful
Converting JSON to Java
but looks like I need to know each and every element of the objects contained. I can write a similar code but before spending so much effort I wanted to check if there is other libraries out there which can do automatic parsing and By just giving the key field I can get those contents.
Jackson should be able to handle the structure with no problem. You do not need to know the exact structure of the JSON. You can just iterate over all of the objects and inter-objects.

Categories

Resources