int arrays to json object in java - java

I'm trying to put two int [] and a double [] in JSON format to send through my java servlet. This is what I have so far.
private JSONObject doStuff(double[] val, int[] col_idx, int[] row_ptr){
String a = JSONValue.toJSONString(val);
String b = JSONValue.toJSONString(col_idx);
String c = JSONValue.toJSONString(row_ptr);
JSONObject jo = new JSONObject();
jo.put("val",a)
jo.put("col",b);
jo.put("row",c);
return jo;
}
But when I print the JSONobject, I get this unreadable result:
{"val":"[D#62ce3190","col":"[I#4f18179d","row":"[I#36b66cfc"}
I get the same result in javascript where I am sending the JSONObject to.
Is there a problem with the conversion from numbers to string? Should I perhaps use JSONArray instead?

It is because the toString method of int[] or double[] is returning the Object's default Object.toString().
Replace with Arrays.toString(int[]/double[]), you will get expected result.
Check this answer for more explantion about toString.

Instead of using
jo.put("val",a)
jo.put("col",b);
jo.put("row",c);
Use;
jo.put("val",val);
jo.put("col",col_idx);
jo.put("row",row_ptr);

Related

JSon disasambly [duplicate]

I have several string each containing a JSON representation of an array of objects. Here's an example in code to illustrate, though this is not my actual code (the JSON strings are passed in):
String s1 = "[{name: "Bob", car: "Ford"},{name: "Mary", car: "Fiat"}]";
String s2 = "[{name: "Mack", car: "VW"},{name: "Steve", car: "Mercedes Benz"}]";
I need to combine those two JSON arrays into one large JSON array. I could treat this as a String manipulation problem and replace the inner end square brackets with commas but that's not particularly robust (though I am guaranteed to get valid JSON).
I'd rather treat these two Strings as JSON arrays and just add them together somehow. It's a great plan except I don't know the "somehow" part.
Does anyone know a solution in Java that doesn't require constructing Java Object representations of the JSON objects?
Thanks!
This code will take sourceArray (s2), and append it to the end of destinationArray (s1):
String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";
JSONArray sourceArray = new JSONArray(s2);
JSONArray destinationArray = new JSONArray(s1);
for (int i = 0; i < sourceArray.length(); i++) {
destinationArray.put(sourceArray.getJSONObject(i));
}
String s3 = destinationArray.toString();
You really have only two choices: parse the JSON (which invariably would involve constructing the objects) or don't parse the JSON. Not parsing is going to be cheaper, of course.
At first glance your idea about treating it as a String-manipulation problem might sound fragile, but the more I think about it, the more it seems to make fine sense. For error detection you could easily confirm that you were really dealing with arrays by checking for the square brackets; after that, just stripping off the ending bracket, adding a comma, stripping off the beginning bracket, and adding the "tail" should work flawlessly. The only exception I can think of is if either array is empty, you should just return the other String unchanged; again, that's very easy to check for as a String.
I really don't think there's any reason to make it more complex than that.
I used this code for Combine two Json Array.
String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";
String s3=new String("");
s1=s1.substring(s1.indexOf("[")+1, s1.lastIndexOf("]"));
s2=s2.substring(s2.indexOf("[")+1, s2.lastIndexOf("]"));
s3="["+s1+","+s2+"]";
System.out.println(s3);
And here is my solution, You may want to merge more than two arrays :
Java version:
public static JSONArray mergeMultiJsonArray(JSONArray... arrays) {
JSONArray outArray = new JSONArray();
for (JSONArray array : arrays)
for (int i = 0; i < array.length(); i++)
outArray.put(array.optJSONObject(i));
return outArray;
}
Kotlin version:
fun mergeMultiJsonArray(vararg arrays: JSONArray): JSONArray {
val outArr = JSONArray()
for (array in arrays)
for (i in 0 until array.length())
outArray.put(array.optJSONObject(i))
return outArr
}
i use this code to append all the elements of a jsonArray to a common JsonArray.
public JSONArray getMergeJsonArrays(ArrayList<JSONArray> jsonArrays) throws JSONException
{
JSONArray MergedJsonArrays= new JSONArray();
for(JSONArray tmpArray:jsonArrays)
{
for(int i=0;i<tmpArray.length();i++)
{
MergedJsonArrays.put(tmpArray.get(i));
}
}
return MergedJsonArrays;
}
This function does the magic, adding multiples arrays returning one JSONArray with all elements
public static JSONArray JoinArrays(JSONArray... jsonArrays) {
JSONArray resultJSONArray = new JSONArray();
Arrays.stream(jsonArrays).forEach(jsonArray -> IntStream.range(0, jsonArray.length()).mapToObj(jsonArray::get).forEach(resultJSONArray::put));
return resultJSONArray;
}
Use Below Method pass all JSON array in ArrayList this method will return cumulative JsonArray
public JSONArray getMergeJson(ArrayList<JSONArray> xyz){
JSONArray result=null;
JSONObject obj= new JSONObject();
obj.put("key",result);
for(JSONArray tmp:patches){
for(int i=0;i<tmp.length();i++){
obj.append("key", tmp.getJSONObject(i)); ;
}
}
return obj.getJSONArray("key");
}

JSON array parsing with Java [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Grabbing JSON objects and adding multiple keys values into a variable

This is an interesting one i wanted to ask what the best approach would be.
Given the json below
{
"day1":2,
"day2":1,
"day3":4
}
Whats the best way of getting the sum of that?
First code i thought would be this
response = is the json above that i get
int value = getValue(response,name);
public static String getValue(String response,name) {
JSONObject result = new JSONObject(response);
Object attribute = result.get(name*);
return attribute.toString();
}
Im at this point and need help. Im thinking doing a while loop but whats the best approach
Like this, you can get sum.
public static Integer getSum(String jsonStr) {
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Set<String> keySet = jsonObject.keySet();
Integer sum = keySet.stream().collect(Collectors.summingInt(k -> (int) jsonObject.get(k)));
return sum;
}

How do you set an integer value with JSONObject in Java?

How do you set the value for a key to an integer using JSONObject in Java?
I can set String values using JSONObject.put(a,b);
However, I am not able to figure out how to use .put() to set integer values. For example:
I want my jsonobject to look like this:
{"age": 35}
instead of
{"age": "35"}.
You can store the integer as an int in the object using put, it is more so when you actually pull and decode the data that you would need to do some conversion.
So we create our JSONObject
JSONObject jsonObj = new JSONObject();
Then we can add our int!
jsonObj.put("age",10);
Now to get it back as an integer we simply need to cast it as an int on decode.
int age = (int) jsonObj.get("age");
It isn't so much how the JSONObject is storing it but more so how you retrieve it.
If you're using org.json library, you just have to do this:
JSONObject myJsonObject = new JSONObject();
myJsonObject.put("myKey", 1);
myJsonObject.put("myOtherKey", new Integer(2));
myJsonObject.put("myAutoCastKey", new Integer(3));
int myValue = myJsonObject.getInt("myKey");
Integer myOtherValue = myJsonObject.get("myOtherKey");
int myAutoCastValue = myJsonObject.get("myAutoCastKey");
Remember that you have others "get" methods, like:
myJsonObject.getDouble("key");
myJsonObject.getLong("key");
myJsonObject.getBigDecimal("key");

converting string into json object

I am getting a string like String s = "abc:xyz". Is there any direct method to convert it into JsonObject having abc as key and xyz as value.
I know there a way by converting string into String s = "{\"abc\":\"xyz\"}" and then I can use JSONObject j =(JSONObject) new JSONParser().parse(s); But I have too large list of string to convert into json object. So i don't want to preprocess to convert into quoted string.
And one more way to split string on : . But i want to know any parser method which convert directly into object. So that i does not have to split. It is also a kind of preprocessing.
If there is any way to convert by passing string to method. please suggest.
It sounds like you just want:
String[] bits = s.split(":");
if (bits.length() != 2) {
// Throw an exception or whatever you want
}
JSONObject json = new JSONObject();
json.put(bits[0], bits[1]);
Split the string on :; use the parts to make your object.

Categories

Resources