GSON - convert a string into a JsonArray - java

I am trying to convert a string into a JsonArray. So far I have tried to do the following:
Gson().toJson(string)
Gson().toJsonTree(string)
both throw an exception saying that the argument is not a JsonArray.
Here is the string, as you can see it is a JsonArray:
"[{\"match\":{\"id\":92757102,\"tournament_id\":3666234,\"state\":\"open\",\"player1_id\":58602461,\"player2_id\":58602459,\"player1_prereq_match_id\":null,\"player2_prereq_match_id\":null,\"player1_is_prereq_match_loser\":false,\"player2_is_prereq_match_loser\":false,\"winner_id\":null,\"loser_id\":null,\"started_at\":\"2017-07-17T19:10:07.588-04:00\",\"created_at\":\"2017-07-17T19:10:07.476-04:00\",\"updated_at\":\"2017-07-17T19:10:07.588-04:00\",\"identifier\":\"A\",\"has_attachment\":false,\"round\":1,\"player1_votes\":null,\"player2_votes\":null,\"group_id\":null,\"attachment_count\":null,\"scheduled_time\":null,\"location\":null,\"underway_at\":null,\"optional\":false,\"rushb_id\":null,\"completed_at\":null,\"suggested_play_order\":1,\"prerequisite_match_ids_csv\":\"\",\"scores_csv\":\"\"}}]"

JsonArray data = (JsonArray) JsonParser.parseString(str);

Gson().fromJson(string, JsonArray::class.java)

toJson() renders a json object as a string (of json).
You want the fromJson() method, which converts a string to a json object.
Try:
new Gson().fromJson(string, JsonArray.class)

Related

Convert String to JSONArray (or any array)

Im trying to parse the following value paramter to a JSONArray (or any other array):
"value":"[{\"fileName\":\"Instructions.docx\",\"filePath\":\"http://someserver/api/files/somefilereference1\"},{\"fileName\":\"Sailing plan.docx\",\"filePath\":\"http://someservert/api/files/somefilereference2\"}]"
As you can see I get the "value" as a string instead of a real array. How can I parse this?
I have tried parsing it to both JSONObject and JSONArray with no success.
Any suggestions?
Ah - I figured it out (feels dumb):
String clean = propertyObject.getString("value").replaceAll("\\\\", "");
JSONArray docArray = new JSONArray(clean);

Receiving JSON response within Double quotes

I am receiving data from the server using Volley, but the received data is coming within double quotes.
"{"Meta Data":{"1. Information":"Daily Prices (open, high, low, close) and Volumes","2. Symbol":"INSI","3. Last Refreshed":"2017-11-24","4. Output Size":"Full size","5. Time Zone":"US/Eastern"},"Time Series (Daily)":{"2017-11-24"....}"
I need to parse this information in order to extract the data but I am unable to convert it into JSONObject. I am clueless.
On using jsonArray = new JSONArray(response);
The debugger says jsonArray is NULL
TIA.
#jyotirmaya ojha, the JSON string that you shared have JSON Object not JSON Array, so the debugger will always say jsonArr is NULL because JSON Object cannot be casted in JSON Array
Please try this instead
JSONObject jsonObj = new JSONObject(response);

Converting json object to json array using org.json.simple

I have one org.json.simple.JSONObject i.e {"2016":
obj = {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}
I want to convert to json array like
org.json.simple.JSONArray arr = obj.toJsonArray(obj); //no such method exists
Is there any method available to convert above object to array.
or do i need to iterate to make it JSONArray.
I am using org.json.simple not org.json.
The String is a JSONObject not JSONArray.
String s = {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}
You can use the following code:
Object obj = parser.parse(s);
JSONObject object = (JSONObject)obj;
Creating JSONArray:
JSONArray list = new JSONArray();
list.add(object);

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

Create a JSONArray

How can I create a JSONArray, since creating a JSONObject is quite simple:
JSONObject j = new JSONObject();
j.put("key",value);
Right now I can put another string in the JSONObject, or a string representation of a JSONObject.
But how can I create a JSONArray and insert it to the JSONObject?
But how can I create a JSONArray and insert it to the JSONObject?
You can create JSONArray same like you have tried to create JSONObject.
Creating time:
For example:
JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);
Retrieving time:
you can fetch the value of String or JSONObject or any by their key name. For example:
JSONArray myArray = objJson.getJSONArray("array");
You can do it like:
String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.toString(data));
Or, create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.
Why dont you use Gson library its very easy to convert any object into json array, json object
Download Gson library then use like
Gson gson=new Gson();
String json=gson.toJson(object);
if Object is of List object it will create json array
Gson gson = new Gson();
reverse parsing for array --
listObject = gson.fromJson(json,
new TypeToken<List<ClassName>>() {
}.getType());
for single object
object = gson.fromJson(json, ClassName.class);

Categories

Resources