How to split all array elements from JSON in Java
{
"id": "405844",
"username": "abc8",
"password_hash": "dkjfhs7rjkds932dajk2900932",
"role": "customer",
"followed_stores" :
[
{
"id": "sda",
"created": {
"date": "2016-06-28 14: 43 : 28",
"epoch": 1467125008563
}
}
],
"followed_influencers": [
{
"id": "sda",
"created": {
"date": " 2016-06-28 14: 43 : 28",
"epoch": 1467125008563
}
}
]
}
I want 3 JSON in 2 json I must have followed_stores array, followed_influencer array and in the last remaining json
You can create an instance of org.json.JSONArray with server response:
String serverResponse = "YOUR STRING";
JSONArray serverJsonArray = new JSONArray(serverResponse);
And then fill products list:
ArrayList<String> products = new ArrayList<>(serverJsonArray.length());
for(int i = 0; i < serverJsonArray.length(); i++){
products.add(serverJsonArray.getString(i));
}
Or if you absolutely want a String array:
String[] products = new String[serverJsonArray.length()];
for(int i = 0; i < serverJsonArray.length(); i++){
products[i] = serverJsonArray.getString(i);
}
Related
So I have an JSON data which looks like this. But I need to invert in one specific scene and one specific element ("iCalstate") its state.
For example if its true, it should overwrite it false. After it has overwritten the specific element it should write this json type to an file called test.json.
{"scene": [
{
"id": 0,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
},
{
"id": 1,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
},
{
"id": 2,
"element": [
{"iCalstate": "false"},
{"iCalstate": "false"}
]
}
]}
What I tried so far:
I have made methods to get the JSONObject & JSONArrays, I tried to create an if which does invert the value (it works). The thing that I didn't manage is to invert it on a specific sceneindex and elemindex --> any help would be gladly appreciated
int sceneindex = 0;
int elemindex = 0;
JSONObject json = new JSONObject();
JSONArray scene = new JSONArray();
JSONArray element = new JSONArray();
JSONArray relement = datain.getIcalSettingsElement(sceneindex); //gets the element from the "olf"
try {
for (int i = 0; i < 1; i++) {
json.put("scene", scene);
JSONObject node = new JSONObject();
scene.put(node);
node.put("id", i);
node.put("element", element);
}
for (int ii = 0; ii < 3; ii++) {
if (ii == elemindex) {
JSONObject enode = new JSONObject();
String invwrite = "";
if (relement.getJSONObject(ii).getString("iCalstate").equals("true")) {
invwrite = "false";
} else if (relement.getJSONObject(ii).getString("iCalstate").equals("false")) {
invwrite = "true";
}
enode.put("iCalstate", invwrite);
element.put(enode);
} else {
JSONObject enode = new JSONObject();
String write = relement.getJSONObject(ii).getString("iCalstate");
enode.put("iCalstate", write);
element.put(enode);
}
}
instead i am getting this it should only write at the first element, where the id is 0, but it's writing to each element:
{"scene": [
{
"id": 0,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
},
{
"id": 1,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
},
{
"id": 2,
"element": [
{"iCalstate": "true"},
{"iCalstate": "false"}
]
}
]}
Create a corresponding POJO for your JSON. And use ObjectMapper to map the JSON string and create an instance. You could then perform your desired operation on that instance.
Following Json needs to group by city to get array along with count if city have same array value. after that I want to sort the 2 biggest and the rest are added together, but how to do it?
{
"data": [
{
"ID": 47,
"city": "Jakarta"
},
{
"ID": 48,
"city": "Bogor"
},
{
"ID": 49,
"city": "Bogor"
},
{
"ID": 50,
"city": "Jakarta"
},
{
"ID": 51,
"city": "Jakarta"
},
{
"ID": 52,
"city": "Bali"
},
{
"ID": 50,
"city": "Lampung"
}
]
}
and i have tried so far is group by city to get array
try {
JSONObject jsonObject = new JSONObject(result);
HashMap<String,Integer> hashMap = new HashMap<>();
for (int i=0;i<jsonObject.getJSONArray("data").length();i++){
JSONObject innerJsonObject = jsonObject.getJSONArray("data").getJSONObject(i);
String key = innerJsonObject.getString("city");
if(hashMap.containsKey(key)){
int count = hashMap.get(key)+1;
hashMap.put(key,count);
}else {
hashMap.put(key,1);
}
}
Log.e("Hashmap---",hashMap.toString());
} catch (JSONException e) {
e.printStackTrace();
}
and the result is :
Bogor = 2
Jakarta = 3
Bali = 1
Lampung = 1
the expected result is :
Jakarta = 3
Bogor = 2
Another city = 2
Try to add that HashMap into TreeMap after the for loop like this
Map<String, Integer> reverseSortedMap = new TreeMap<String,
Integer>(Collections.reverseOrder());
reverseSortedMap.putAll(hashMap);//your hashMap with count of city
System.out.println("Reverse Sorted Map : " + reverseSortedMap);
I want to split the value 08:41:19 from below json response. How to split the value?
{
"parameters": [
{
"name": "CurrentLocalTime",
"value": "2019-05-29 08:41:19",
"dataType": 4,
"parameterCount": 1,
"message": "Success"
}
],
"statusCode": 200
}
Try this,
JSONArray jSONArray = inputJSON.getJSONArray("parameters");
int length = jSONArray.length();
for (int i = 0; i < length; i++) {
JSONObject jSONObject= jSONArray.getJSONObject(i);
System.out.println(jSONObject.get("value").split("\\s")[1]);
}
My code works for parsing json objects to a single textview now I want to change it to parse the first object to text Response and the second to text Response2
thats why I changed the for loop to i < = 1 so I can get only the first 2 results from the array I dont need the rest. the for loop works on 1 field but I think there is something wrong with my if /else loop
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
jsonResponse2 ="";
for (int i = 0; i <= 1; i++) {
//int i <= 1
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
if (i <=0){
jsonResponse += "Name: " + name + "\n\n";
}
else { jsonResponse2 += "Name: " + name + "\n\n";}
}
txtResponse.setText(jsonResponse);
txtResponse2.setText(jsonResponse2);
JSON
[
{
"name": "Ravi Tamada",
"email": "ravi8x#gmail.com",
"phone": {
"home": "08947 000000",
"mobile": "9999999999"
}
},
{
"name": "Tommy",
"email": "tommy#gmail.com",
"phone": {
"home": "08946 000000",
"mobile": "0000000000"
}
},
{
"name": "Roy",
"email": "roy8#gmail.com",
"phone": {
"home": "01944000000",
"mobile": "6600000000"
}
},
{
"name": "Sami",
"email": "sami69#gmail.com",
"phone": {
"home": "08006 104400",
"mobile": "7700000000"
}
}
]
May this resolve your problem:
String name1,name2,name3,name4;
JSONArray jArray=new JSONArray(result);
for(int i=0;i<jArray.length();i++){
if(i==0){
name1=jArray.getJSONObject(i).getString("name");
Log.e("Name First", name1);
}else if(i==1){
name2=jArray.getJSONObject(i).getString("name");
Log.e("Name Second", name2);
}else if(i==2){
name3=jArray.getJSONObject(i).getString("name");
Log.e("Name Third", name3);
}else if(i==3){
name4=jArray.getJSONObject(i).getString("name");
Log.e("Name Four", name4);
}
}
// txtResponse.setText(name1);
// txtResponse2.setText(name2);
Where "result" is your json array string.
The json string generated from the media server looks like this
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"albums": [
{
"albumid": 1,
"albumlabel": "",
"artist": [
"www.SongsLover.pk"
],
"artistid": [
2
],
"description": "",
"genre": [
"Pop"
],
"label": "Single 2012",
"rating": 0,
"style": [
""
],
"thumbnail": "image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fbackup%20Music%2fSissle2%2fGangnam%20Style%20.mp3/",
"title": "Single 2012",
"type": "",
"year": 0
},
{
"albumid": 164,
"albumlabel": "",
"artist": [
"ARrahman","MJ"
],
"artistid": [
146,163
],
"description": "",
"genre": [
"Soundtrack"
],
"label": "Lord of the rings",
"rating": 0,
"style": [
""
],
"thumbnail": "image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fExtras_Test%2fEnakkena%20Yenave.mp3/",
"title": "Lord of the rings",
"type": "",
"year": 2000
},{..........},{........},{........}
],
"limits": {
"end": 155,
"start": 0,
"total": 155
}
}
}
The following is the code i tried using Java. Iam getting the json response as Input stream and using jsonreader to parse the json response. But here in the above json, the artist dictionary has array values without names.
JsonReader reader = new JsonReader(new InputStreamReader(inputStream,
"UTF-8"));
ArrayList<Integer> albumId = new ArrayList<Integer>();
ArrayList<String> artistId = new ArrayList<String>();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equalsIgnoreCase("result")) {
reader.beginObject();
while (reader.hasNext()) {
String check = reader.nextName();
if (check.equalsIgnoreCase(type)) {
reader.beginArray();
int i = 0;
while (reader.hasNext()) {
i++;
reader.beginObject();
int albumid;
String artistid = null;
while (reader.hasNext()) {
name = reader.nextName();
if (name.equalsIgnoreCase("albumid")) {
albumid = reader.nextInt();
albumId.add(albumid);
} else if (name
.equalsIgnoreCase("artist")) {
reader.beginArray();
while(reader.hasNext()){
artistid = reader.nextString();
artistId.add(artistid);
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
//}
}
Log.i(LOGCAT, Integer.toString(i));
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
} else {
reader.skipValue();
}
}
reader.endObject();
So, the problem for me is how to get the array values from the artist dictionary with the above code. Please help me in this. Thanks in advance.
// Try this way,hope this will you to solve your problem...
String respone = "{\"id\":1,\"jsonrpc\":\"2.0\",\"result\":{\"albums\":[{\"albumid\":1,\"albumlabel\":\"\",\"artist\":[\"www.SongsLover.pk\"],\"artistid\":[2],\"description\":\"\",\"genre\":[\"Pop\"],\"label\":\"Single 2012\",\"rating\":0,\"style\":[\"\"],\"thumbnail\":\"image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fbackup%20Music%2fSissle2%2fGangnam%20Style%20.mp3/\",\"title\":\"Single 2012\",\"type\":\"\",\"year\":0},{\"albumid\":164,\"albumlabel\":\"\",\"artist\":[\"ARrahman\",\"MJ\"],\"artistid\":[146,163],\"description\":\"\",\"genre\":[\"Soundtrack\"],\"label\":\"Lord of the rings\",\"rating\":0,\"style\":[\"\"],\"thumbnail\":\"image://music#smb%3a%2f%2fCECOTS-NAS%2fMedia%2fMusic%2fExtras_Test%2fEnakkena%20Yenave.mp3/\",\"title\":\"Lord of the rings\",\"type\":\"\",\"year\":2000}],\"limits\":{\"end\":155,\"start\":0,\"total\":155}}}";
ArrayList<HashMap<String,Object>> albumList = new ArrayList<HashMap<String, Object>>();
try{
JSONObject responseJson = new JSONObject(respone);
JSONArray albumJsonArray = responseJson.getJSONObject("result").getJSONArray("albums");
for (int i=0;i<albumJsonArray.length();i++){
HashMap<String,Object> album = new HashMap<String, Object>();
album.put("albumid",albumJsonArray.getJSONObject(i).getString("albumid"));
album.put("albumlabel",albumJsonArray.getJSONObject(i).getString("albumlabel"));
JSONArray artistJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("artist"));
ArrayList<String> artistList = new ArrayList<String>();
for (int j=0;j<artistJsonArray.length();j++){
artistList.add(artistJsonArray.getString(j));
}
album.put("artist",artistList);
JSONArray artistidJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("artistid"));
ArrayList<String> artistidList = new ArrayList<String>();
for (int j=0;j<artistidJsonArray.length();j++){
artistidList.add(artistidJsonArray.getString(j));
}
album.put("artistid",artistidList);
album.put("description",albumJsonArray.getJSONObject(i).getString("description"));
JSONArray genreJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("genre"));
ArrayList<String> genreList = new ArrayList<String>();
for (int j=0;j<genreJsonArray.length();j++){
genreList.add(genreJsonArray.getString(j));
}
album.put("genre",genreList);
album.put("label",albumJsonArray.getJSONObject(i).getString("label"));
album.put("rating",albumJsonArray.getJSONObject(i).getString("rating"));
JSONArray styleJsonArray = new JSONArray(albumJsonArray.getJSONObject(i).getString("style"));
ArrayList<String> styleList = new ArrayList<String>();
for (int j=0;j<styleJsonArray.length();j++){
styleList.add(styleJsonArray.getString(j));
}
album.put("style",styleList);
album.put("thumbnail",albumJsonArray.getJSONObject(i).getString("thumbnail"));
album.put("title",albumJsonArray.getJSONObject(i).getString("title"));
album.put("type",albumJsonArray.getJSONObject(i).getString("type"));
album.put("year",albumJsonArray.getJSONObject(i).getString("year"));
albumList.add(album);
}
for (HashMap<String,Object> album:albumList){
System.out.println("Album Id : "+album.get("albumid").toString());
System.out.println("Album Label : "+album.get("albumlabel").toString());
System.out.println("Album Description : "+album.get("description").toString());
System.out.println("Label : "+album.get("label").toString());
System.out.println("Rating : "+album.get("rating").toString());
System.out.println("Thumbnail : "+album.get("thumbnail").toString());
System.out.println("Title : "+album.get("title").toString());
System.out.println("Type : "+album.get("type").toString());
System.out.println("Year : "+album.get("year").toString());
System.out.println("Artist size : "+((ArrayList<String>)album.get("artist")).size());
System.out.println("Artist Id size : "+((ArrayList<String>)album.get("artistid")).size());
System.out.println("Genre size : "+((ArrayList<String>)album.get("genre")).size());
System.out.println("Style size : "+((ArrayList<String>)album.get("style")).size());
}
}catch (Throwable e){
e.printStackTrace();
}
You can use JsonPath to extract the artist arrays.
e.g. "$.result.albums[*].artist".
JsonSurfer would be a good choice if you are handling large json because it uses streaming parser without loading whole json into the memory.
The code is short with JsonSurfer.
JsonSurfer jsonSurfer = JsonSurfer.gson();
Collection<Object> result = jsonSurfer.collectAll(inputStreamReader, "$.result.albums[*].artist");