Create a JSONArray - java

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

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.

Java: Extract json values as individuals

I have this json in java:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.
Is there an easy way to extract all the values as individuals like jsonObj [1]?
You may Use Gson parsing library as below :
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
or simply use:
example
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
for Array use :
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)

How do i preserve the original order of json with JSONArray

I am using the JSONArray object and I am passing to the constructor of that object a string. The string that I'm passing is
[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}].
After out-printing the json object, I get the following:
[{"charcount":22,"w":53.09,"x":18.43,"y":30.47,"fontSize":11,"bold":0,"id":349133}].
Can I get an example in code of how I can preserve the order of the original json string?
You can use a an ordered collection to parse your json to keep it's order.
A sample for your json:
String json = "[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}]";
Gson gson = new Gson();
Type type = new TypeToken<Set<LinkedTreeMap<String, Object>>>() {}.getType();
Set<LinkedTreeMap<String, Object>> myMap = gson.fromJson(json, type);
System.out.println(json);
System.out.println(myMap);

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

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.

Categories

Resources