Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am getting the following String response from a server:

{"fid":"1272","uri":"http://someurl/services/file/1272"}

I need to convert it into a JSONArray. Any help?

By the way, I tried this and it does not work:

String response=getResponseFromServer();
JSONArray array = new JSONArray(response);

I get the error:

org.json.JSONException: Value {"fid":"1272","uri":"http://someurl/services/file/1272"} of type org.json.JSONObject cannot be converted to JSONArray
share|improve this question
 
Have you tried anything? Are you using a JSON Library? –  jlordo Jun 9 at 17:21
2  
THis is a JSON OBJECT, not a JSON array –  fge Jun 9 at 17:21
 
It is a Java String, not a JSON object yet. He's doing Java, not Javascript. –  marlenunez Jun 9 at 17:40
 
Seems like you're using the JSON library from org.json, have you checked my answer? –  keelar Jun 9 at 18:01
add comment

closed as not a real question by jlordo, The New Idiot, bensiu, Reno, Soner Gönül Jun 10 at 5:52

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 1 down vote accepted

If you're talking about using the JSON in java library, then since your input string is a JSON object, not a JSON array, you should first load it using JSONObject:

String response=getResponseFromServer();
JSONObject jsonObject = new JSONObject(response);

After that, you can use toJSONArray() to convert a JSONObject to JSONArray given an array of key strings:

String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
share|improve this answer
 
Ok. Thanks. JSONObject was new to me. –  Inf Min Jun 9 at 18:31
1  
No problem, you're welcome. That's what stackoverflow for :) –  keelar Jun 9 at 21:50
add comment

If you do a search right here on StackOverflow for Java String to JSONArray, you should get this answer: Converting from JSONArray to String then back again

JSONArray jArray;
String s = jArray.toString(); // basically what you have ;)
JSONArray newJArray = new JSONArray(s);
share|improve this answer
 
The string I have is not in the format that the JSONArray constructor accepts. –  Inf Min Jun 9 at 17:31
 
Ok, so see @keelar's answer in that case. –  marlenunez Jun 9 at 17:38
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.