Represent JSON as an array of objects in JAVA - java

I would like to create a JSON string as an array of objects like this:
[
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
The JAVA JSON objects put method looks like this: jsonObject.put(String key, Collection value);
When I enter my key and collection, my json looks like this:
{
"JSONObject": [
{
"alertid": "1",
"alerttext": "This is test",
"alertdate": "2010-02-11 09:03:40"
},
{
"alertid": "2",
"alerttext": "Another alert",
"alertdate": "2010-02-11 09:11:04"
}
]
}
How can I get my json string to look like the first string when I am constrained to the signature of the put method?

If you're using the net.sf.json library, make yourself a JSONArray and put JSONObjects in it instead.
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("alertid","1");
array.add(obj);

What you need is a JSONArray that you can then fill with JSONObject's
Try something like this:
JSONArray arr = new JSONArray();
for (JSONObject item : collection)
{
arr.put(item);
}
Or, if you already have a Collection of JSONObject's, you can simply write:
JSONArray arr = new JSONArray(yourFancyCollection);
Then, arr.toString() will look like you asked.

Related

Parsing through JSON and selecting multiple items in java

I currently have this JSON:
[
{
"example": "12345678",
"test": "0",
"name": "tom",
"testdata": "",
"testtime": 1531209885613
},
{
"example": "12634346",
"test": "43223452234",
"name": "jerry",
"testdata": "pawenkls",
"testtime": 1531209888196
}
]
I am trying to parse through the array to find a value of "testdata" that matches the value of "testdata" that I have generated, which I am currently doing like so:
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
JsonElement dataHash = ((JsonObject)entries.get(i)).get("dataHash");
Then I wish to find the value of "example" that is in the same array as the "testdata" with the value "pawenkls".
How do I search for the "example" value that is in the same group as the value of "test data" that I have found?
You need to run through the objects in the array and check the value of the testData field against yours. Then read its example field.
String testData = "pawenkls";
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
String example = null;
for(JsonElement dataHashElement : entries) {
JsonObject currentObject = dataHashElement.getAsJsonObject();
if(testData.equals(currentObject.get("testdata").getAsString())) {
example = currentObject.get("example").getAsString();
break;
}
}
System.out.println("example: "+example);
This prints out
example: 12634346
Here is a Java 8 version doing the same thing:
String testData = "pawenkls";
JsonObject[] objects = new Gson().fromJson(blockchainJson, JsonObject[].class);
Optional<JsonObject> object = Arrays.stream(objects)
.filter(o -> testData.equals(o.get("testdata").getAsString()))
.findFirst();
String example = null;
if(object.isPresent())
example = object.get().get("example").getAsString();
System.out.println("example: "+example);

Is there a way to name each JSONObject in an array?

{
"Object1": {
"description": "An object",
"data": "more data"
},
"Object2": {
"description": "An object",
"data": "more data"
}
}
How would I use GSON to iterate over the elements in this JSON Object to easily parse each element one by one?
Yes there is, but PrabhakarP is right, associative arrays in JSON are objects. So in your case,
{
"Object1": {
"description": "An object",
"data": "more data"
}
}
You would have a meta-object containing each array element as a property, which doesn't really make sense. You should parse it differently.
But if you still need, in GSON, then try ,
JsonArray body = gson.fromJson(yourString, JsonArray.class);
JSONObject metaObj = new JSONObject();
for (JsonElement currEle : paymentsArray) {
JSONObject currObj = currEle.getAsJsonObject();
String nameVal = currObj.get("name");
currObj.remove("name");
metaObj.addProperty(nameVal, currObj);
}
I would suggest you to add a property to each object in array and use it
I looked at the man page and found I could loop over the set of members in the object.
JsonObject obj = gson.fromJson(jsonFile, JsonObject.class);
for(Map.Entry<String, JsonElement> element : obj.entrySet()) {
Object obj = gson.fromJson(element.getValue(), Object.class);
// do stuff with the object
}

Convert JsonArrayString to List<String> or String[]

How to convert a JsonArrayString to List<String> or String[]? I tried to use Gson to covert it, but I failed. Maybe I overlooked some existing methods which can do this? Any other better way to make it or can someone give me some tips?
[
{
"test": "test"
},
{
"test": "test"
},
{
"test": "test",
"test2": "test2",
"test3": [
{
"test": "test"
},
{
"test": "test"
}
]
}
]
I guess you dont know if the value is a JSONObject or a JSONArray. In thise case you may want to use a Map and a Object as Value like this (not tested).
class Model {
private Map<String, Object> test;
}
Take care that you have to validate if the Value is a JSONArray or a JSONObject using (for example):
if (this.getTest().getValue() instanceof JSONObject.class) { ... }
I Finally find the way to resovel:
// Converting JSON String array to Java String array
String jsonStringArray = "[{\"test\":\"test1\"},{\"test\":\"test2\"},{\"test\":\"test3\",\"test2\":[{\"test\":\"test1\"},{\"test\":\"test2\"}]}]";
// creating Gson instance to convert JSON array to Java array
Gson converter = new Gson();
Type type = new TypeToken<List>() {
}.getType();
List list = converter.fromJson(jsonStringArray, type);
// convert List to Array in Java
System.out.println("Java List created from JSON String Array - example");
System.out.println("JSON String Array : " + jsonStringArray);
System.out.println("Java List : " + list);
// let's now convert Java array to JSON array -
String toJson = converter.toJson(list);
System.out.println("Json array created from Java List : " + toJson);
output:
Java List created from JSON String Array - example
JSON String Array : [{"test":"test1"},{"test":"test2"},
{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]
Java List : [{test=test1}, {test=test2}, {test=test3, test2=[{test=test1}, {test=test2}]}]
Json array created from Java List : [{"test":"test1"},{"test":"test2"},{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]

Android: Dynamically Get JSON Array Key Name From JSON

I have a json link, if we open it I get a following result
{
"Status": "Success",
"All_Details": [{
"Types": "0",
"TotalPoints": "0",
"ExpiringToday": 0
}],
"First": [{
"id": "0",
"ImagePath": "http://first.example.png"
}],
"Second": [{
"id": "2",
"ImagePath": "http://second.example.png"
}],
"Third": [{
"id": "3",
"ImagePath": "http://third.example.png"
}],
}
What I need is, I want to dynamically get all the key names like status, All_details, First etc.
And I also want to get the data inside the All_details and First Array.
I used following method
#Override
public void onResponse(JSONObject response) throws JSONException {
VolleyLog.d(TAG, "Home Central OnResponse: " + response);
String statusStr = response.getString("Status");
Log.d(TAG, "Status: " + statusStr);
if (statusStr.equalsIgnoreCase("Success")) {
Iterator iterator = response.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
}
}
}
I get all the key names in get stored in the String key. But I am unable to open get the values inside the JSON array, for eg. I need to get the values inside first and second array using the String(Key). How can I do that.???
First, to get the keynames, you can easily iterate through the JSONObject itself as mentioned here:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( response.get(key) instanceof JSONObject ) {
System.out.println(key); // do whatever you want with it
}
}
Then, to get the values of the array:
JSONArray arr = response.getJSONArray(key);
JSONObject element;
for(int i = 0; i < arr.length(); i++){
element = arr.getJSONObject(i); // which for example will be Types,TotalPoints,ExpiringToday in the case of the first array(All_Details)
}
If you want to get the JSON array from the response JSONObject you can use the JSONArray class. JSONObject has a method to get a JSONArray: getJSONArray(String). Remember to catch the JSONException when trying this. This exception will be thrown if there is no key for example.
Your code could look like this (only the while loop):
while (iterator.hasNext()) {
String key = (String)iterator.next();
try {
JSONArray array = response.getJSONArray(key);
// do some stuff with the array content
} catch(JSONException e) {
// handle the exception.
}
}
You can get the values from the array with the methods of JSONArray (see the documentation)
Something like this will allow you to iterate on array and individual fields once you have extracted the keys using what you have done. Instead of "Types" use the key variable you will create before this.
JSONArray allDetails = response.getJsonArray("All_Details")
for (int i = 0 ; i < allDetails.length(); i++) {
JSONObject allDetail = allDetails.getJSONObject(i);
allDetails.getString("Types");
}
First of all I want to inform you that it's not a valid JSON. Remove the last Comma (,) to make it valid.
Then you can Iterate like here
JSONArray myKeys = response.names();
Try this one
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
try {
String dynamicKey = (String) keys.next();//Your dynamic key
JSONObject item = jsonObject.getJSONObject(dynamicKey);//Your json object for that dynamic key
} catch (JSONException e) {
e.printStackTrace();
}
}

Parsing JSON Android ArrayList

I apologize if the title of my question is a bit misleading.
I created a POJO to hold CholesterolInformation about a user (HDL, LDL, Triglycerides, units, etc...). I now want to use my JSONObject to create an ArrayList so that I can generate some data points.
My JSONObject contains the following:
{
"cholesterol": [
{
"date": "2014-01-01",
"hdl": "56464.0",
"ldl": "46494.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "5.0",
"ldl": "5.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "6.0",
"ldl": "6.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
}
]
}
My question is, how would one go about iterating through this JSON Object? I would like to maybe use a for each, and create a new object to add to the ArrayList in each iteration... Do you have any advice or suggestions?
Note: I have never used the JSONObject before, and thus am not too familiar with its usage.
EDIT: Thanks everybody, that was exactly what I was looking for. I need to get more familiar with JSON manipulation. And I will look into GSON as well!
Use GSON as suggested by Eric as you already created POJO.
Gson gson = new Gson();
Type type = new TypeToken<List<POJO>>() {}.getType();
List<POJO> mList = gson.fromJson(your_json_string_here, type);
It's time to learn some JSON manipulation:
JSONArray array = yourJsonObject.optJSONArray("cholesterol");
if (array != null) {
for (int i=0; i< array.length; i++) {
JSONObject object = array.optJSONObject(i);
if (object != null) {
// this is where you manipulate all the date, hdl, ldl...etc
}
}
}
you also should check for null before accessing the json
If I understand you correctly, you want to create an ArrayList of your POJO? I assume you have getters and setters inside your POJO class. Initialize an ArrayList somewhere near the top like this
private ArrayList<CholesterolInformation> mCholesterol;
Now, parse through your json like this
JSONobject data = new JSONObject(jsonStringData);
JSONArray cholesterol = data.getJSONArray("cholesterol");
for(int i = 0; i < cholesterol.length; i++)
{
JSONObject object = cholesterol.getJSONObject(i);
// Create a new object of your POJO class
CholesterolInformation ci = new CholesterolInformation();
// Get value from JSON
String date = object.getString("date");
// Set value to your object using your setter method
ci.setDate(date);
String hdl = object.getString("hdl");
ci.setHdl(hdl);
.....
.....
// Finally, add the object to your arraylist
mCholesterol.add(ci);
}

Categories