how i can get data from Json object and array - java

I get the request but i can't get the jsonarray from json object.
JSONObject ob = JSONObject.fromObject(response.toString());
JSONArray arr = ob.getJSONArray("results");
for (int i = 0; i < arr.size(); i++) {
JSONObject jsonAuth = arr.getJSONObject(i);
String PREFIX = jsonAuth.get("PREFIX").toString();
}
my json:
{
"d": {
"results": [{
"__metadata": {
"type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
"uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('d76fffbe-8c3b-4c66-bd7f-16c9d099d143')"
},
"SEC_ID": "d76fffbe-8c3b-4c66-bd7f-16c9d099d143",
"PREFIX": "B",
"TIPO_NCF": "01",
"NUM_FROM": 50,
"NUM_TO": 100,
"NUM_CURRENT": 25,
"VALID_UNTIL": "\/Date(1556582400000)\/",
"CAJA": "b1c913fc-e319-476f-8295-64782b77de52"
}, {
"__metadata": {
"type": "ceodo.cco.loc_do.OdataV2.SecuenciasType",
"uri": "com:443/ceodo/cco/loc_do/OdataV2.xsodata/Secuencias('f3323600-6bf2-4e90-8856-56390595d748')"
},
"SEC_ID": "f3323600-6bf2-4e90-8856-56390595d748",
"PREFIX": "B",
"TIPO_NCF": "02",
"NUM_FROM": 1,
"NUM_TO": 100,
"NUM_CURRENT": 35,
"VALID_UNTIL": "\/Date(1554249600000)\/",
"CAJA": "c90030fb-030b-4a99-929a-adc72eaf082f"
}]
}
}

Well, you can call the 'd' object first.
The sequence of your json file should be from a d(JSONObject) tag to a results(JSONArray) tag.
Here is code by using another json library
import org.json.JSONArray;
import org.json.JSONObject;
... skip ...
//JSONObject ob = JSONObject.fromObject(resBuf.toString());
JSONObject ob = new JSONObject(resBuf.toString());
if(ob.has("d"))
{
JSONObject dobj = ob.getJSONObject("d");
if(dobj.has("results"))
{
JSONArray arr = dobj.getJSONArray("results");
System.out.println(arr.length());
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonAuth = arr.getJSONObject(i);
String PREFIX = jsonAuth.get("PREFIX").toString();
System.out.println(PREFIX);
}
}
}

Related

Split time value from json using java

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

Android Empty List

I am trying to fill a ListView inside an Async Task!
all_items = gson.toJson(profile);
this is the rest
try {
JSONObject object = new JSONObject(all_items);
JSONArray ja = object.getJSONObject("tree").getJSONArray("children");
for (int i = 0; i < ja.length(); i++) {
JSONObject object1 = ja.getJSONObject(i);
if (object1.has("name") && object1.has("percentage")) {
System.out.println(object1.has("name"));//nothing gets printed
HashMap<String, Object> tmp = new HashMap<>();
tmp.put("name", object1.get("name"));
tmp.put("percentage", object1.get("percentage"));
array_list.add(tmp);
}
}
}catch(JSONException e){
e.printStackTrace();
}
Json Array is in this format:
This new code is not outputing nothing,no lists is shown The Json is in this format
{
"id": "*UNKNOWN*",
"processed_lang": "en",
"source": "*UNKNOWN*",
"tree": {
"children": [
{
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Adventurousness",
"name": "Adventurousness",
"percentage": 0.6317251869427992,
"sampling_error": 0.0550028572
No Error is thrown however the list is still empty.
there are basically 3 more children array inside the children array. Your code just gets the top level children and tries to find the attributes inside it
try {
JSONObject object = new JSONObject(all_items);
JSONArray ja = object.getJSONObject("tree").getJSONArray("children");
for (int k = 0; k < ja.size(); k++) {
JSONObject lvlOne = ja.getJSONObject(k);
JSONArray lvlOneArray = lvlOne.getJSONArray("children");
for (int j = 0; j < lvlOneArray.size(); j++) {
JSONObject lvlTwo = lvlOneArray.getJSONObject(i);
JSONArray lvlTwoArray = lvlTwo.getJSONArray("children");
for (int i = 0; i < lvlTwoArray.length(); i++) {
JSONObject object1 = lvlTwoArray.getJSONObject(i);
if (object1.has("name") && object1.has("percentage")) {
System.out.println(object1.has("name"));//nothing gets printed
HashMap<String, Object> tmp = new HashMap<>();
tmp.put("name", object1.get("name"));
tmp.put("percentage", object1.get("percentage"));
array_list.add(tmp);
}
}
}catch(JSONException e){
e.printStackTrace();
}

Java , put JsonObject into JsonArray, but JsonArray take the same value at the end of the for loop

I am a novice in Java, on this code I am trying to put JsonObect in a JsonArray , but the things is the JsonArray only takes the last value and it is duplicate in it.
You do not need to understand all the code just the interesting part
I have put the part Of the code which is interesting in the field //******here******// code //******end here******// and I have also put the json file if you want to test
For my part ,I have tried to put my values in List of JsonObject then put it in the JsonArray,but I have the same result.
I have also tried to use a Hash map with indices but it still do not working
If you print the JsonObject variable "Alldate" you can see that it has different values but When I put them in the JsonArray Array "ArrayBuckets", you will see That the JsonArray has the same value which is the last values.
I do not understand because my jsonObject and Array are in the same loop.
Thanks .
Here is the code :
package jsonbi.bi;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.gson.Gson;
public class JsonBi9 {
JSONParser parser = new JSONParser();
JSONObject json;
Object obj;
Map.Entry<String, JsonNode> field;
HashMap newmap = new HashMap();
JsonFactory factory = new JsonFactory();
private ObjectMapper mapper = new ObjectMapper();
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray();
JSONObject Alldate = new JSONObject();
JSONObject BucketsObject = new JSONObject();
JSONObject Groupe = new JSONObject();
JSONObject Aggregations = new JSONObject();
JSONObject TheJson = new JSONObject();
JSONArray ArrayBuckets = new JSONArray();
Hashtable ht = new Hashtable();
int j =0;
public JsonBi9() {
try {
// here I am readind the json file
obj = parser.parse(new FileReader("myjson2.json"));
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(obj.toString());
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.getFields();
JSONObject jsonObject = new JSONObject(obj.toString());
// here I am reading the fields in the json fields
while (fieldsIterator.hasNext()) {
field = fieldsIterator.next();
newmap.put(field.getKey(), field.getValue());
if (field.getKey().equals("aggregations")) {
System.out.println("hugo");
JSONObject aggregations = jsonObject.getJSONObject("aggregations");
JSONObject groupe = aggregations.getJSONObject("groupe");
JSONArray buckets = groupe.getJSONArray("buckets");
for (int i11a = 0; i11a < buckets.length(); i11a++) {
JSONObject obj1bucket = buckets.getJSONObject(i11a);
JSONObject date11 = obj1bucket.getJSONObject("date");
JSONArray obj11bucket = date11.getJSONArray("buckets");
List<String> listSubbucket = new ArrayList<String>();
for (int i11 = 0; i11 < obj11bucket.length(); i11++) {
listSubbucket.add(obj11bucket.getJSONObject(i11).toString());
// System.out.println(obj11bucket.getJSONObject(i11).toString());
}
jsonArray = new JSONArray();
for (int i11 = 0; i11 < listSubbucket.size(); i11++) {
JSONObject SubBucket = new JSONObject();
SubBucket.put("buckets", listSubbucket.get(i11));
getdocument(obj1bucket, Alldate);
//******************************here ********************************//
// System.out.println(SubBucket);
Alldate.put("date", SubBucket);
ArrayBuckets.put(Alldate);
//*µµ if you want to print the jsonObject and array
// System.out.println(Alldate);
// System.out.println(ArrayBuckets);*
//*********************************end here ******************************//
} // end first for loop
} //end second for loop
Enumeration e = ht.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement());
getdocument(groupe, Groupe);
Groupe.put("buckets", ArrayBuckets);
Aggregations.put("groupe", Groupe);
// System.out.println(Aggregations);
} // fin du if
else {
// System.out.println("Key: " + field.getKey() + "\tValue:"
// + field.getValue());
TheJson.put(field.getKey(), field.getValue());
} // fin du else
} // fin du while
// I put all the documents
TheJson.put("aggregations", Aggregations);
System.out.println(TheJson);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getdocument(JSONObject obj1bucket, JSONObject Alldate) {
// get the json documents in the subbuckets
int i = 0;
// JSONObject buckectinfos1 = new JSONObject();
for (Iterator key = obj1bucket.keys(); key.hasNext();) {
Object jsonkeys;
try {
jsonkeys = obj1bucket.get((String) key.next());
Object jsonvalues = obj1bucket.names().getString(i);
String jsonInString = gson.toJson(jsonkeys);
if (!jsonkeys.getClass().getName().equals("org.json.JSONObject")
&& !jsonkeys.getClass().getName().equals("org.json.JSONArray")) {
} // fin du if
i++;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // fin du for
}
}
Here is the values in the JsonObject "alldate" that I want to put In the JsonArray "ArrayBuckets":
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T00:00:00.000Z\",\"doc_count\":1,\"value\":{\"value\":1},\"key\":1493769600000}"},"doc_count":"1","key":"\"a\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":2,\"value\":{\"value\":3},\"key\":1493776800000}"},"doc_count":"1","key":"\"a\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T00:00:00.000Z\",\"doc_count\":4,\"value\":{\"value\":5},\"key\":1493769600000}"},"doc_count":"4","key":"\"b\""}
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"},"doc_count":"4","key":"\"b\""}
But I only have the last value duplicated in the JsonArray "ArrayBuckets":
{"date":{"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"},"doc_count":"4","key":"\"b\""}
Here is the Json file :"myjson2.json"
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 10,
"max_score": 0,
"hits": []
},
"aggregations": {
"groupe": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "a",
"doc_count": 1,
"date": {
"buckets": [
{
"key_as_string": "2017-05-03T00:00:00.000Z",
"key": 1493769600000,
"doc_count": 1,
"value": {
"value": 1
}
},
{
"key_as_string": "2017-05-03T01:00:00.000Z",
"key": 1493776800000,
"doc_count": 2,
"value": {
"value": 3
}
}
]
}
},
{
"key": "b",
"doc_count": 4,
"date": {
"buckets": [
{
"key_as_string": "2017-05-03T00:00:00.000Z",
"key": 1493769600000,
"doc_count": 4,
"value": {
"value": 5
}
},
{
"key_as_string": "2017-05-03T01:00:00.000Z",
"key": 1493773200000,
"doc_count": 5,
"value": {
"value": 6
}
}
]
}
}
]
}
}
}
Here is the result of the code :
{
"_shards":"{\"total\":5,\"failed\":0,\"successful\":5}",
"hits":"{\"hits\":[],\"total\":10,\"max_score\":0}",
"took":"7",
"timed_out":"false",
"aggregations":{
"groupe":{
"doc_count_error_upper_bound":"0",
"sum_other_doc_count":"0",
"buckets":[
{
"date":{
"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
},
"doc_count":"4",
"key":"\"b\""
},
{
"date":{
"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
},
"doc_count":"4",
"key":"\"b\""
},
{
"date":{
"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
},
"doc_count":"4",
"key":"\"b\""
},
{
"date":{
"buckets":"{\"key_as_string\":\"2017-05-03T01:00:00.000Z\",\"doc_count\":5,\"value\":{\"value\":6},\"key\":1493773200000}"
},
"doc_count":"4",
"key":"\"b\""
}
]
}
}
}
You can only have one entry whith a name inside a JSONObject.
for (int i11 = 0; i11 < listSubbucket.size(); i11++) {
JSONObject SubBucket = new JSONObject();
SubBucket.put("buckets", listSubbucket.get(i11));
getdocument(obj1bucket, Alldate);
// System.out.println(SubBucket);
Alldate.put("date", SubBucket);
ArrayBuckets.put(Alldate);
//*µµ if you want to print the jsonObject and array
// System.out.println(Alldate);
// System.out.println(ArrayBuckets);
} // end first for loop
When you do this, in each loop you overwrite de value whith the key "date". If you want to have all your date in AllDate it have to be a JSONArray.
You can also replace Alldate.put("date", SubBucket); by Alldate.put("date" + i, SubBucket);
Instead of declaring Alldate variable in the class scope, declare it in for loop. The error occurs because you have only one variable JsonObject to put to JsonArray. So the solution is to create each different JsonObject variable for each loop.
for (int i11 = 0; i11 < listSubbucket.size(); i11++) {
JSONObject Alldate = new JSONObject();
...
//******************************here ********************************//
// System.out.println(SubBucket);
Alldate.put("date", SubBucket);
ArrayBuckets.put(Alldate);
or something that fit your code.

Not able to parse JSON Array properly

I am getting the following as a String response from a webserveice:
[
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
]
In Java I am trying to do the following:
JSONArray jArray = new JSONArray(result);
System.out.println("Response: "+jArray);
for(int i = 0; i<= jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
However I am getting the following exception:
JSON Exception: org.json.JSONException: Value
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
at 0 of type org.json.JSONArray cannot be converted to JSONObject
JSON Exception: org.json.JSONException: Index 1 out of range [0..1)
I am following this example. Where am I going wrong? Also notice the missing long brackets in the exception snippet.
You have two arrays, one is within another:
[
[
//Your objects
]
]
You could either change data format so it only has one array, or modify your code:
JSONArray outer = new JSONArray(result);
JSONArray jArray = outer.getJSONArray(0);
jArray JSONArray contain another JSONArray which contain JSONObeject so first get JSONArray and then get all JSONObject from it:
JSONArray oneArray = jArray.getJSONArray(i);
for(int j = 0; j<= oneArray.length(); j++){
JSONObject oneObject = oneArray.getJSONObject(j);
// get dgtype,subtypename,subtypedesc,.. from oneObject
}
As it says, 'JSONArray cannot be converted to JSONObject', You have an array in another array, so
JSONArray jArray1 = new JSONArray(result);
then
JSONArray jArray = jArray1.getJSONArray(0);
Now it will work.
for(int i = 0; i<= jArray.length(); i++){
final JSONArray innerArray = jArray.getJSONArray(i);
for (int a = 0; a < innerArray.length(); a++) {
try {
final JSONObject oneObject = innerArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
}

Parsing Facebook FQL Multiquery in Java

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

Categories