I do have such piece of code:
List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
if (userIdentifiers.isEmpty()) {
LOG.info(No users to verify.");
return;
}
VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[0]);
I'm getting an error:
java.lang.ArrayStoreException
at java.util.ArrayList.toArray(ArrayList.java:133)
I cannot convert list to array. Any ideas what could be wrong?
I have also tried:
VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[userIdentifiers.size()]);
This type of exception happens when you try to store different type of the object in the array.
Refer the below link
Oracle doc
This works for me..Please check
List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
VersionedUserIdentifier[] vui=(VersionedUserIdentifier[])userIdentifiers.toArray();
Stream.of(vui).forEach(System.out :: println);
Related
I am getting a json string back from the local test server as following.
[0,"000SSSBBBB"]
I am not able to fetch the "000SSSBBBB" using JSON object. My code is as following. At run time at following line exception comes as following :
"value 0 at 0 of type java.lang.Integer can not be converted to jsonobject"
JSONObject obj = jsonArray.getJSONObject(i);
Please help as i am new to json.
Thanks
It is not a JSONObject that's why you are facing with that Exception.
Java doc is sometimes helpful: http://www.json.org/javadoc/org/json/JSONObject.html
JSONObject getJSONObject(int index)
Get the JSONObject associated with an index.
You should use :
java.lang.Object get(int index)
Get the object value associated with an index.
or
java.lang.String getString(int index)
Get the string associated with an index.
Don't forget to provide a length check before to take an element a given position.
You can do it by that following code for example: jsonArray.length() == 1
You can try this!
This [0,'000SSSBBBB'] is one object without a key, the object contains an array!
try {
JSONArray jsonArray = new JSONArray("[0,'000SSSBBBB']");
String obj = (String)jsonArray.get(1);
...
}catch(org.json.JSONException e){}
I have run in to an issue, while converting my iOS app to android.
The database is structured such that there are "stations", these stations can have multiple images attached, in the parse database, the images are an array of imagePointers.
When i wanted to get the images out in iOS here is what i did:
stations = object in this case
// Get a single image
if ([[object objectForKey:#"imagePointers"] objectAtIndex:0] != [NSNull null]) {
PFFile *imageFile = [[[object objectForKey:#"imagePointers"] objectAtIndex:0] objectForKey:#"image"];
cell.coverImageView.file = imageFile;
[cell.coverImageView loadInBackground];
}
Its pretty simple, i just lift the imagePointers array and get objectAtIndex0, then i cast it to a parse file.
But i can't do this in android, here is what i have atm:
JSONArray imagePointers = thisStation.getJSONArray("imagePointers");
try {
JSONObject indexImage = imagePointers.getJSONObject(0);
} catch ( Exception e ) {
JSONObject indexImage = null;
}
Here i get the object at index 0 as a JSONObject, i cannot use this in a ParseFile Object, since i need to cast it as a generic type ParseFile.
How do i do this? Or is my approach completely incorrect?
Fixed it by avoiding casting to JSON, apparently there is a getList method
// Get parse Image as index image
ParseObject thisStation = stationItems.get(position);
List<ParseObject>imagePointers = thisStation.getList("imagePointers");
ParseFile image = imagePointers.get(0).getParseFile("image");
thumbnail.setParseFile(image);
thumbnail.loadInBackground();
I had the same issue for almost 2 days but finally I solved it by the getList method!
Now all you gotta do is use getList instead of getJSONObject or getJSONArray or whatever, because when you use them you will not be able to use the getParseFile for any of those believe me.
But instead you can do something like:
val obj = parseObject.getList("listname")
val file = obj[0].getParseFile("image")
Now, I don't remember how the syntex is or so but the key here is to use the getList method if you want to get list of all images you saved in a Back4app Parse JSONArray.
Hope you found it helpful.
Goodluck
I am getting the following exception
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Java.CompileFile.doCompilation(CompileFile.java:48)
at GUI.CompilerForm.compileBtnActionPerformed(CompilerForm.java:225)
at GUI.CompilerForm.access$400(CompilerForm.java:23)
............
I no the error is at line 48 in CompileFile.java, it is saying that the array in NULL and i dont know why because that is where i am adding strings to it!
String[] compile;
int numberOfErrors = 0;
.
.
.
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
String errors = diagnostic.getKind().toString()+" on line "+ diagnostic.getLineNumber() +"\nIn file: \n"+ diagnostic.toString();
compile[numberOfErrors] = errors;
numberOfErrors++;
}
I have tried System.out.println(errors); straight after i set it and it is working fine so i really dont know what is going on!
Any suggestions?
You've declared a variable called compile, but you haven't shown anywhere that it's given a value. Assuming it's an instance variable, its value will default to null. You need to initialize it with:
compile = new String[someSize];
where someSize is "big enough".
Alternatively, and preferrably, you could use a list:
// TODO: Rename variable to something more sensible
private final List<String> compile = new ArrayList<String>();
then...
compile.add(errors);
Then you can probably get rid of numberOfErrors too, as that would just be compile.size() presumably.
From the code snap you are showing, it seems you did not initialize compile, so it is initialized to null as default.
You should explicitly create a String[] and assign it to compile:
compile = new String[MY_SIZE];
If you are trying to append errors, you might want to consider using a dynamic array - which is an ArrayList<String> in java for it, and append elements, using ArrayList.add(element)
I guess you haven't initialized the array (properly)
String[] compiled = new String[size];
or you haven't set a proper size of the array
If you are unable to predict how many items there will be in the array. Use lists (eg ArrayList) instead
List<String> compiled = new ArrayList<String>();
Arraylists have no size limit.
To add items
compiled.add(item);
It looks like you haven't initialized your array.
Try something like this :
compile = new String[numberOfErrors];
And then store the errors in the array.
I am getting a casting exception every time I attempt to get an array of entities out of list of entities that I pull back from a jpa call. Example...
QuickLaunch[] qLaunchArr = null;
List<QuickLaunch> listQL = null;
try
{
System.out.println("testing 1..2..3");
//qLaunchArr
listQL = emf.createNamedQuery("getQuickLaunch").getResultList();
Object[] objArr = listQL.toArray();
//System.out.println(listQL.size());
qLaunchArr = (QuickLaunch[]) listQL.toArray();
}
catch (Exception e)
{
System.out.println("Bull Hockey!!!! I can't believe it's not butter!: "+e.toString());
}
[Ljava.lang.Object; incompatible with [Lcom.upmc.esdm.messaging.entities.QuickLaunch;
That was in my server logs... (I am using WID)
and I also get this exception...
commonj.connector.runtime.DataHandlerException: CWLAP0507E: The response bean class for java class method GetAllQuickLaunchComponents cannot be created. Reason java.lang.IllegalArgumentException: argument type mismatch.
You can try TypedQuery to get the list of entities without explicit casting & prevent exceptions.
TypedQuery<QuickLaunch> listQL = em.createNamedQuery("QuickLaunch.getQuickLaunch", QuickLaunch.class);
List<QuickLaunch> products = listQL .getResultList();
Also, changed query name to identify its class or result type in more meaningful way.
Alright... I think I found the answer. It was inspired by this post...
https://stackoverflow.com/a/8060077/729820
I basically do this
try
{
System.out.println("testing 1..2..3");
listQL = emf.createNamedQuery("getQuickLaunch").getResultList();
System.out.println("What is the size of this list: number "+listQL.size());
qLaunchArr = listQL.toArray(new QuickLaunch[listQL.size()]);
}
All exceptions seem to clear right up.
Thanks for the help guys.
This isn't to do with JPA but Java, as it will not cast Object[] to QuickLaunch[]. Can you not use the Object array instead of a QuickLaunch[] array?
I am passing a json object from javascript to a java servlet using ajax.
var jsonObj = JSON.stringify(objArray); //Then I pass it to Java using ajax.
In my Java I am getting the json string from the request, then creating a jsonarray, then looping through that array and i'm getting errors when trying to pull one of the json objects from the array.
String dataObj = request.getParameter("obj");
String sql = request.getParameter("sql");
ArrayList<Object> returnArray = new ArrayList<Object>();
int key;
//Get type of object being passed.
JSONArray jsonArray = JSONArray.fromObject(dataObj);
for(int i=0; i<jsonArray.size(); i++) {
String obj = new Gson().toJson(jsonArray.getJSONObject(i)); //This is where i'm getting an error
String className = getClassName(jsonArray.getJSONObject(i));
Class targetClass = null;
try {
targetClass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Create Object
Object data = new Gson().fromJson(obj, targetClass);
I'm posting the relevant code, the for loop isn't closed because the rest of the code is quite long, and this is the part where i'm getting the error.
net.sf.json.JSONException: JSONArray[0] is not a JSONObject.
Here is what the json array looks like when its passed in from javascript. This is a println of the jsonArray object.
[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":0}]
With one object in it, this code works. But as soon as I get 2 or more, my error comes up.
[[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":1},{"number":"(555) 555-1233","type":"Mobile","contactId":1,"id":16656,"className":"beans.PhoneNumber","position":0},{"number":"(999) 999-9999","type":"Home","contactId":1,"id":16664,"className":"beans.PhoneNumber","position":3},{"number":"(222) 222-2222","type":"Home","contactId":1,"id":16666,"className":"beans.PhoneNumber","position":4}]]
It almost looks like when i'm passing more than one object, it create an array of an array, which could be why its not working. But how do I avoid doing that when i'm passing a jsonarray from javascript? Using just the dataObj I have no access to size or get to loop through it.
[
[
{
"number":"(123) 456-7050","type":"Home",
"contactId":1,
"id":16662,
"className":"beans.PhoneNumber",
"position":1
},
{
"number":"(555) 555-1233",
"type":"Mobile",
"contactId":1,
"id":16656,
"className":"beans.PhoneNumber",
"position":0
},
{
"number":"(999) 999-9999",
"type":"Home",
"contactId":1,
"id":16664,
"className":"beans.PhoneNumber",
"position":3
},
{
"number":"(222) 222-2222",
"type":"Home",
"contactId":1,
"id":16666,
"className":"beans.PhoneNumber",
"position":4
}
]
]
This is not an array of objects. This is an array of arrays of objects. According to your description, you are expecting something like the following to be fed to your Java:
[{"foo":"bar"}, {"bar":"baz"}]
But you are really trying to parse:
[[{"foo":"bar"}, {"bar":"baz"}]]
I am not completely sure, because you have not shared the json that you are trying to parse, but the most probable error you have is just what it says: the first element of the array is not JSONObject. Note that string values, lons and booleans are not JSONObjects. I would suggest you to use the more genereal JSONArray.get and check instance of what class it is. Maybe this can head you to the problem with the json you have. If I got it completely wrong - write back and I will try to help. In such a case it will be still useful to share the results of the proposed experiment.
EDIT:
This is double array -> maybe you using getJSONArray(int index) will help you. as the other answer mentioned - this is array of arrays. Also consider changing the javascript to reduce the level of arrays included.