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.
Related
I have a JSON Content in a String and sometimes it has numeric tags which has to be removed.
Below is a sample JSON content
{
"Test": {
"P1": false,
P2": {
"2000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"4000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"5000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"8000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"6000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
]
},
"P3": "XYZ",
"P4": ABC,
"VL": "",
"PL": [{
"start_date": 1496480880.0,
"id": "TEST1"
}
],
},
"PS": "AMD",
"links": [{
"LOC": "en-US",
"PS": "AMD"
}, {
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
In the above case "P2" tag has numeric keys and in such case we need to display it as after converting the string to JSON. Which means, we need to remove the tags which has numeric keys.
I have tried with org.json, org.json.simple and com.gson as well but nothing seems to work.
I am able to read each line using the below code snipet
public static void printJson(JsonElement jsonElement) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
try{
Integer.parseInt(en.getKey());
break;
}catch(NumberFormatException ex){
if("".equals(str)){
str = "\"" + en.getKey() + "\": {";
}else{
str = str + "\"" + en.getKey() + "\": {";
}
System.out.println(en.getKey() + "-----" + en.getValue());
}
printJson(en.getValue());
}
}
}
// Check whether jsonElement is Arrary or not
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
for (JsonElement je : jarr) {
printJson(je);
}
}
// Check whether jsonElement is NULL or not
else if (jsonElement.isJsonNull()) {
// print null
System.out.println("null");
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
if("".equals(str)){
str = "\"" + jsonElement.getAsString() + "\"";
}else{
str = str + "\"" + jsonElement.getAsString() + "\"";
}
System.out.println(jsonElement.getAsString());
}
}
But am unable to remove the numeric keyed tags. Can someone please help me with this.
If you want to strip JSONObject keys that are numeric, you can do it like this:
private static void strip(JSONObject obj) {
for (Iterator<String> keyIter = obj.keys(); keyIter.hasNext(); ) {
String key = keyIter.next();
if (key.matches("\\d+"))
keyIter.remove();
else
strip(obj.get(key));
}
}
private static void strip(Object value) {
if (value instanceof JSONObject) {
strip((JSONObject) value);
} else if (value instanceof JSONArray) {
for (Object elem : (JSONArray) value)
strip(elem);
}
}
Test
String input = new String(Files.readAllBytes(Paths.get("path/to/file.json")), StandardCharsets.US_ASCII);
JSONObject obj = new JSONObject(input);
strip(obj);
System.out.println(obj.toString(2));
Output
{
"PS": "AMD",
"Test": {
"P1": false,
"P2": {},
"P3": "XYZ",
"P4": "ABC",
"VL": "",
"PL": [{
"id": "TEST1",
"start_date": 1.49648088E9
}]
},
"links": [
{
"LOC": "en-US",
"PS": "AMD"
},
{
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
I got the solution with Andreas help.
But I had another issue while working on it. It was working fine for 2-3 levels only. After 3rd level, if there are any numeric keys, they were not being removed.
I have added one more condition to check if the object is an instance of org.json.JSONObject and then check if that JSONObject has any JSONArray.
Sample code given below
if (value instanceof org.json.JSONArray) {
for (int i=0; i< ((org.json.JSONArray) value).length(); i++) {
try{
if(((org.json.JSONArray) value).get(i).getClass().getName() =="org.json.JSONObject"){
strip((JSONObject) ((org.json.JSONArray) value).get(i));
}
}catch(Exception ex){
}
}
}
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);
}
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");
This question already has answers here:
Android how to sort JSONArray of JSONObjects
(6 answers)
Closed 9 years ago.
How to sort a JSONArray of objects by object's field?
Input:
[
{ "ID": "135", "Name": "Fargo Chan" },
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
];
Desired output (sorted by "Name" field):
[
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
{ "ID": "135", "Name": "Fargo Chan" },
];
Try this:
//I assume that we need to create a JSONArray object from the following string
String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
The sorted JSONArray is now stored in the sortedJsonArray object.
I'm having some trouble with parsing an FQL multiquery for Facebook. I don't know how I need to handle the JSONArray with the same name in the result -> fql_result_set. Here is the FQL JSON I got.
{
"data": [
{
"name": "query1",
"fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
]
},
{
"name": "query2",
"fql_result_set": [
{
"uid": uid1,
"name": "name1",
"pic_square": "pic1"
},
{
"uid": uid2,
"name": "name2",
"pic_square": "pic2"
},
{
"uid": uid3,
"name": "name3",
"pic_square": "pic3"
}
]
}
]
}
Here is what I got at the moment in my Java code, but I get nothing in return. The data I get, will eventually go in an ArrayList.
try {
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray data = jso.getJSONArray("data");
for(int i = 0; i < data.length(); i++){
JSONObject o1 = data.getJSONObject(i);
JSONArray rs1 = o1.getJSONArray("fql_result_set");
for(int j = 0; j < rs1.length(); j++){
JSONObject rso1 = rs1.getJSONObject(j);
String uid = rso1.getString("uid");
String eid = rso1.getString("eid");
String rsvp = rso1.getString("rsvp_status");
}
JSONObject o2 = data.getJSONObject(i);
JSONArray rs2 = o2.getJSONArray("fql_result_set");
for(int k = 0; k < rs2.length(); k++){
JSONObject rso2 = rs2.getJSONObject(k);
String name = rso2.getString("name");
String pic = rso2.getString("pic_square");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Does anyone know how I need to parse this JSON result?
Thanks in advance!
Solution
try {
people = new ArrayList<Person>();
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray data = jso.getJSONArray("data").getJSONObject(0)
.getJSONArray("fql_result_set");
JSONArray data2 = jso.getJSONArray("data").getJSONObject(1)
.getJSONArray("fql_result_set");
for (int i = 0; i < data.length(); i++) {
Person p = new Person();
JSONObject o1 = data.getJSONObject(i);
uid = o1.getString("uid");
p.setUserId(uid);
p.setRsvp_status(o1.getString("rsvp_status"));
for (int j = 0; j < data2.length(); j++) {
JSONObject o2 = data2.getJSONObject(j);
if (p.getUserId().equals(o2
.getString("uid"))) {
p.setName(o2.getString("name"));
p.setPic(o2.getString("pic_square"));
}
}
people.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
// assign the whole result to a JSON Object
JSONObject result = whatever-variable-name
// get 'data' JSONArray
JSONArray array = result.getJSONArray('data')
// loop
for(i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
**
name = obj.getString('name');
}
** at this point obj is "name": "query1",
"fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
]
and name has the value query1 or query2 depending on the loop count. You could you the methods used so far to gain access to fql_result_set": [
{
"uid": uid1,
"eid": eid1,
"rsvp_status": "attending"
},
{
"uid": uid2,
"eid": eid2,
"rsvp_status": "attending"
},
{
"uid": uid3,
"eid": eid3,
"rsvp_status": "attending"
}
] GLHF!
Try this:
String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString();
String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString();
jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set");
jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set");