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.
Related
This question already has answers here:
Get json array keys in android
(5 answers)
Closed 7 years ago.
I need to get a key name of JsonArray, so JSON looks like this, please not, that JSON is starting with array brackets, and inside it it has objects, that was made i guess because back end will have the ability to add objects.
[
{
"tehnology": [ ]
},
{
"science": []
}
]
So i need to get the names from it "technology" and "science", because json can dynamically change, how can I implement it?
The JSONArray contains JSONObjects. Retrieve every JSONObject and use keys() to access the key defined in every JSONObject
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject object = jArray.optJSONObject(i);
Iterator<String> iterator = object.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
}
}
This question already has answers here:
Gson handle object or array
(4 answers)
Closed 7 years ago.
Using Gson, I am trying to force my json objects to have an array value with one element. Although I construct the json this way, the JsonParser creates a new JsonObject in place of my array of length 1. The majority of json in my system have value with arrays greater than length 1 and parse correctly.
I discovered this while attempting a utility method for brute forcing a JsonObject to JsonArray. It's not working out as I would expect.
static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if(object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
System.out.println("broken: " + object.toString());
JsonObject temp = object.get(key).getAsJsonObject();
String fixed = "{'" + key + "':[" + temp.toString() + "]}";
System.out.println("pre-fix: " + fixed);
//parsing here reduces the array to an object - hot to prevent?
temp = new JsonParser().parse(fixed).getAsJsonObject();
System.out.println("fixed: " + object.toString());
return object.get(key).getAsJsonArray();
}
}
output:
broken: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}
pre-fix: {'token':[{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}]}
fixed: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}
An example of the majority json as they appear correctly in the system:
{"token":[{"Speaker":"PER0","POS":"IN","lemma":"except","CharacterOffsetBegin":742.0,"NER":"O","id":1.0,"word":"Except","CharacterOffsetEnd":748.0},{"CharacterOffsetEnd":752.0,"Speaker":"PER0","POS":"IN","lemma":"for","CharacterOffsetBegin":749.0,"NER":"O","id":2.0,"word":"for"},{"id":3.0,"word":"extra","CharacterOffsetEnd":758.0,"Speaker":"PER0","POS":"JJ","lemma":"extra","CharacterOffsetBegin":753.0,"NER":"O"},{"Speaker":"PER0","POS":"NN","lemma":"meat","CharacterOffsetBegin":759.0,"NER":"O","id":4.0,"word":"meat","CharacterOffsetEnd":763.0},{"CharacterOffsetEnd":764.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":763.0,"NER":"O","id":5.0,"word":"."}]}
Is there a clever way out of this problem - some way I can effectively force my objects into arrays so I can process them in stream without too much try/catch or if/else handling?
static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if (object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
JsonArray oneElementArray = new JsonArray();
oneElementArray.add(new JsonObject());
return oneElementArray;
}
}
Although, you shouldn't work with JsonObject/JsonArray directly. Make a POJO class for your data and use Gson to deserialize JSON.
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;
}
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");
}
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);