alternative to JSONObject in java - java

I've been using JSONObject as return types on most of my classes and methods for android to aid in debugging and informing the user of the problems. But I've been trying to build an AsyncTask JSONObject has been getting quirky. Is there any multi-type array that can be used to transport primitive data-types in one object?

Perhaps using a
Bundle
would be helpful?
http://developer.android.com/reference/android/os/Bundle.html

If the type doesnt need to be preserved, you could always convert your data to Strings and transport that instead. Then you could use whatever you want; an array, an ArrayList, etc.
If you need to preserve the type, you can use a second value to denote the type. Oryou could still use whatever data structure fits your needs performance-wise and store Object instances; Character for chars, Integer for ints, etc. and then on retrieval, use reflection to get their type info.

Without knowing a little more info, I'd possibly look into using Gson since you say that JSONObject has been quirky for you. I've been using it and haven't had any problems so far:
http://code.google.com/p/google-gson/

Related

Sending object from python to java

In Python i have a class with some string attributes and a function that returns an object of this class with atttributes set (sometimes can return an array of objects).
Theres any way to get this return in Java? Where i can see the strings of the object?
I Tried Jython but couldnt make it work!
Use json.dump function in Python to serialize your object into json format. Then use something like json.org library in Java to parse this object into Java object, some example over here.
Mind that not every object might be serializable, in general data structures like dictionaries or lists are easily serializable, from your description it seems like you want to move an instance of an object from one program into another, which is not possible to be done automatically and requires human work in rewriting the code as instances of classes contain not only data but also functions (methods).
Good luck!

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.

javax.json objects have same methods, but they're not implementations of a common interface. How to cast?

I'm dealing with the strange javax.json library. So here's the problem:
I need to cast an Object of type JsonValue to either JsonObject or JsonArray so I can call the methods getJsonObject and getJsonArray of it. Both JsonArray and JsonObject have the same method names with the same functionalities but they're not implemented methods, they are methods defined on each of them! See: JsonObject, JsonArray.
The obvious solution would be to verify the type and then cast depending on the verified type, like this:
if (current.getValueType().equals(JsonValue.ValueType.OBJECT)) {
current = ((JsonObject) current).getJsonObject(node);
} else if (current.getValueType().equals(JsonValue.ValueType.ARRAY)) {
current = ((JsonArray) current).getJsonObject(node);
}
but it'd require too many repetitions on my code. So I ask:
1) If both JsonObject and JsonArray have the same methods, why they're not implementations of some interface?
2) Is there a more elegant way to cast the object to JsonObject or JsonArray at the same time by using some trick? Do you know any way to make this situation better?
Although the 2 methods on the 2 different objects have the same name, their signatures are in fact different. JsonObject#getJsonObject(String) accepts a String key identifying the value to pull from a JSON object of key-value pairs. JsonArray#getJsonObject(int) accepts an int index identifying which element to pull the value from in a JSON array.
In this case, there is no appropriate common interface that the 2 classes can share. Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly.
Since the 2 methods in question do not have the same signature, there are not other alternatives for calling them in a "common way". You could potentially use reflection, but this risks making the code more confusing. For example, Apache Commons includes MethodUtils#invokeMethod. You could potentially use that to invoke any method named "getJsonObject", accepting any kind of object (either String or int). Although using this would make it "common code" across both cases, it's potentially confusing for people reading the code later. They'd have to keep track of the fact that this is using reflection, and that the passed argument might be either String or int, and that it really all works out thanks to it being either a JSON object or array. Instead, I would favor just doing the downcast in this case.
Chris is right, Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly. However, if you are ok with adding an external library, I would recommend gson for parsing Json
This library has JsonElement class which should fit good in your case. look at this to see how it works

Java: Processor costs of converting from object to other data types

I'm working on a Java project where I handle a list of items, where each item has an id of type int and a value of type String. Then I have another type called ItemCollection which internally has the list and exposes methods to add, remove, get items, etc.
The application is a Financial Transaction Gateway, so we're very focused on performance, since the application will receive many transactions per second. My question is:
The cost of converting an String to another type, like Integer, Char, Date, etc. is the same of converting an Object containing an Integer, Char, Date, etc.?
To clarify, currently the value of the Item is handled in String format. The item has a method called getValue() that returns the item's value in String. But sometimes this value has to be converted to another type, for example int. So what I'm planning to do is change the root type of the value to Object and expose methods like getString(), getInt(), getDate(), getChar(), etc., where the value will be converted from Object to the specific data type. Of course, if the value can't be converted will return null/zero/etc.
In your experience, what would be the best approach?
Is the same to convert from Object to int than String to int?
If you need great performance than I cat suggest that it will be much better to use lower level language like C++. Maybe it is appropriate to use functional language like Erlang. If you want to work with Java then you should avoid taged types and use type system provided by the language. Taged classes are not much faster then actual java classes. Tagged classes are outdated programming style in Java. If you need to convert String to Date, for examle, then this operation will be much slower then cast performed by instanceof operator. Also in Java there is Stop the world GC pause, which can be deadly for real time applications.
Based on the level of detail you've provided, my suggestion is: don't do it!.
Find a way to model your data using Java's type system. Avoid type conversions (e.g. String to Integer), and avoid type casting (e.g. (String)someObject).
If you have a question about a specific operation (such as Integer's toString function), then I suggest consulting the documentation or the source code.
Who is producing these objects? Are they not coming in to you in some format such as JSON or XML that you can actually marshal the data to their real types?
For example, if you receive a JSON message of something like:
date: 2012-12-25
acct: 12345
amount: 123.50
then it's at that point where you should be putting them in to the correct types.
It seems like you want to dispatch messages or perform actions on items based on their type, and you're trying to convert them using the type. I hate not to answer your question, but how do you hope to accomplish this? Do you first try to see if the item is a Date? and then if not, try to see if it is a number? What takes precedence?
If you have an Item that needs processing.. and you can (as I said before, by marshalling the input data in to different types, not Strings) get a StringItem and a DateItem, for example, you can use the Visitor pattern.
This depends on what you mean by 'convert'. That is not a precise term of art in Java.
If you mean 'cast', then the answer is that casting is fast. Your ItemCollection class might have a method like this:
public int getInt(int index) {
Object value = getObject(index);
return (Integer)value;
}
The cast will add a few machine instructions.
If you mean something more like 'parse', then the answer is that parsing is hundreds or thousands of times slower than casting, but still fast compared to I/O. If you were parsing, your code might look like:
public int getInt(int index) {
String value = getString(index);
return Integer.parseInt(value);
}
So, what exactly do you mean by 'convert'?

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