I'm trying to cast a JSONObject to JSONArray. The JSONObject contains an object of type JSONArray. The array is a sequence of strings. One of the strings in the sequence is formatted as the following.
"uid=\u00d1\u0088\u00d1\u0084\u00d1\u0088"
after doing a cast of the JSONObject to an array the characters in the array change.
"uid=???" T
After the cast to JSONArray the original double byte characters in the above \u format change to the incorrect display characters in my java program. Any ideas? Has anyone seen this problem? I have done some searching but have not come up with answers to my problem.
The code below is what't used to do this.
public static String[] read(JSONObject input)
{
com.ibm.TEPS.JSON.Any.assertTypeCode(input, _type);
JSONArray val = (JSONArray)input.get(FW_Properties.TEPSREST_TYPE_EXT_VAL);
String [] result = new String[val.size()];
for(int i = 0;i<result.length;i++)
{
result[i] = (String)val.get(i);
}
return result;
}
Related
I am trying to parse a JSON Array which looks something like this
"data":["data1","data2","data3"]
If I write JSONArray arr = obj1.getJSONArray("data");, this will provide me with the JSON array but since the key name from key-value pair is missing, how will I retrieve "data1", "data2" and "data3"?
JSON arrays allows for non json children. In this case, the children are of String value:
for(int i=0;i<arr.length();i++) {
String value = arr.getString(i);
}
My syntax might be inaccurate
Assuming this is your JSON,
{"data":["data1","data2","data3"]}
Use the following to retrieve the array,
JSONArray arrJson = jsonData.getJSONArray("data");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
arr[i] = arrJson.getString(i);
}
Is it possible to convert from the newer EJB JSON libraries to the older org.json ones without having to rely on org.json.simple or GSON?
In the case below, "buttons" is a populated JsonArray and I'm trying to copy it into a JSONArray for legacy code. But the initialization of JSONArray from a stringified value always fails with "A JSONObject text must begin with '{'" because a quote is seen as a first character rather than a curly brace.
JSONArray newButtons = new JSONArray();
for (int i = 0; i < buttons.size(); i++) {
JsonString button = buttons.getJsonString(i);
newButtons.put(new JSONArray(button.toString()));
}
return new JSONArray(newButtons);
It doesn't seem like there is any kind of org.json object that I can initialize from a string constructor with a toString() value from the javax.json library. I have managed to move data from org.json structures to javax.json ones, but not vice versa. Is the org.json library too inflexible to do this?
I haven't tried it, but I believe following should work.
JSONArray newButtons = new JSONArray();
for (int i = 0; i < buttons.size(); i++) {
JsonObject button = buttons.getJsonObject(i);
newButtons.put(new org.json.JSONObject(button.toString()));
}
return newButtons;
With the following line you get first the object with index 'i' and then make a JSON String out of it. Your original code rather returns the element 'i' as a value instead of an object.
JsonString button = buttons.getJsonObject(i).toString();
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
The following code is printing hash values instead of Array
JSONObject myjson1 = new JSONObject(expectedResult);
Iterator x = myjson1.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x);
}
The output is as follows:
java.util.HashMap$KeyIterator#42a0b130
java.util.HashMap$KeyIterator#3c2a5fb9
java.util.HashMap$KeyIterator#6e68bc46
java.util.HashMap$KeyIterator#3223cb64
java.util.HashMap$KeyIterator#256c426b
PS: Converting Json to Array (key : value) form
Do not use (String) instead use toString()
So
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x.toString());
And if you want to convert it to string array:
String[] result = jsonArray.values().toArray(new String[0]);
And you can check this one:
how to covert map values into string in Java
I suggest you to use Gson library to manage .json files. It's more accurate, it's more user-friendly and it works very well.
By the way you're asking Java to print the object "x" (Iterator). An object contains the reference to the memory allocation of itself.
You have to ask your software to convert it in a human-readable format, such as String is.
So try to add .toString() method after x invocation.
Try to do something like:
JSONObject myjson1 = new JSONObject(expectedResult);
Iterator x = myjson1.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(myjson1.get(key));
System.out.println(x.toString());
}
I hope to be helpful.
i have this JSON object:
{"error":null,
"result":[{"id":"1234567890",
"count":1,
"recipients":
["u3848",
"u8958",
"u7477474"
],
"dateCreated":"2012-06-13T09:13:45.989Z"
}]
}
and I'm trying to find a way to correctly parse the recipients array into a String[] object.
is there an easy way to do this?
EDIT:
found this answer that has all the things needed for result: Sending and Parsing JSON Objects
the way to do what I wanted was this:
JSONArray temp = jsonObject.getJSONArray("name");
int length = temp.length();
if (length > 0) {
String [] recipients = new String [length];
for (int i = 0; i < length; i++) {
recipients[i] = temp.getString(i);
}
}
You can try to use xstream with json serializer. Take a look this link
I always suggest my favorite library json-lib to handle JSON stuffs.
You can use JSONArray to convert to Object[], although it's not String[], you can still use it because every Object has toString() method.
String sYourJsonString = "['u3848', 'u8958', 'u7477474']";
Object[] arrayReceipients = JSONArray.toArray (JSONArray.fromObject(sYourJsonString));
System.out.println (arrayReceipients [0]); // u3848
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");
}