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

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);

Related

How to set array value in the jsonobject

I am getting the array values as
I need to construct the object as jsonObject.
So I have added like below but the returning object as an error.
How can I add the array as expected in the users.
Note: Here I am sending the users in array from a fragment to set the values in my payload
private String mUserArray; //value =["user1", "user2"]
mUserArray is added in the constructor.
final JsonArray array = new JsonArray();
array.add(mUserArray1);
final JsonObject jo = new JsonObject();
jo.addProperty("type", "value")
jo.add("usernames" , array); // If i set the userarray it failed to convert Added like this as well//new JsonPrimitive(mUserArray1)
return jo;
Expected Result:
{"type": "value", "usernames":["user1", "user2"]}
Actual Result:
{"type":"value","usernames":"[\"user1\", \"user2\"]"}
It seems like that you added the usernames property as a string literal rather than as a JSON array. You can construct a JsonArray of strings from a Java array the following way.
String[] userArray = {"user1", "user2"};
JsonArray userJsonArray = new JsonArray();
for(String user: userArray){
userJsonArray.add(new JsonPrimitive(user));
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "value");
jsonObject.add("usernames", userJsonArray);
Note that JsonObject::addProperty only adds primitives to the JSON object rather than arrays or objects.

GSON - convert a string into a JsonArray

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)

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Put a Java Map to JSON

I have a map of string objects and keys that I wish to put to a json file. I have read that the way to do it is by converting it to an array, and it only works with maps where both the object and key are strings. I can create a JSONObject from the map fine, but cannot put that to an array. Can someone tell me why this does not work?
private static final String JSON_USER_VOTES = "user_votes";
private Map<String, String> mCheckedPostsMap; //This is populated elsewhere
JSONObject obj=new JSONObject(mCheckedPostsMap);
JSONArray array=new JSONArray(obj.toString()); // <<< Error is on this line
json.put(JSON_USER_VOTES, array);
Here is the error:
org.json.JSONException: Value {"232":"true","294":"true"} of type org.json.JSONObject cannot be converted to JSONArray
If you want all of initial map entries enclosed in one JSON object, you can use:
JSONArray array = new JSONArray().put(obj);
This will produce something like
[{"key1:"value1","key2":"value2"}]
If you want each of initial map entries as different JSON object, you can use:
JSONObject obj = new JSONObject(map);
JSONArray array = new JSONArray();
for(Iterator iter = obj.keys(); iter.hasNext(); ){
String key = (String)iter.next();
JSONObject o = new JSONObject().put(key, map.get(key));
array.put(o);
}
This will produce something like
[{"key1:"value1"}, {"key2":"value2"}]

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