I'm using Google Cloud Firestore API for a project that involves simple retrieval of data from the server database. Having set up everything I can't seem to figure out how to properly parse the returned JSON, as all of my attempts have been unsuccessful.
Using the Firestore package is out of question as this is a defined project.
I have tried the classic approach since Android studio only gets the field part with its HTTPURLConnection.
This is the JSON structure:
{
"documents": [
{
"name": "projects/...",
"fields": {
"name": {
"stringValue": "Q1"
},
"myValues": {
"arrayValue": {
"values": [
{
"stringValue": "First"
}
]
}
},
"index": {
"integerValue": "0"
}
},
"createTime": "2019-05-24T10:07:10.864421Z",
"updateTime": "2019-05-28T07:52:34.445600Z"
}
]
}
Here's my attempt at parsing it:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks=0;
String qName="";
ArrayList<String> answerList= new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
if (jObject.has("index")) indeks = jObject.getInt("index");
if (jObject.has("name")) qName= jObject.getString("name");
JSONArray answerArray= jObject.getJSONArray("myValues");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
Database structure
I expect that all of the documents get parsed and added to the list ArrayList but it seems like nothing happens and I can't find the TAG in the Logcat.
It looks you're trying to get index before accessing its parent fields.
if (jObject.has("index")) indeks = jObject.getInt("index");
In this line you should have gotten before the parent object fields, otherwise you will not have access to index or name.
EDIT
I've been checking your code and you are parsing some things wrong.
Let's go step by step:
You are trying to access to the childs of fields without accessing to their parent.
The solution following your structure would be something like this:
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
You're trying to access also the myValues array not respecting the objects hierarchy. The correct way should be something like this:
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer = answerArray.getJSONObject(i).getString("stringValue");
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
With this changes I have been able to parse the Json you posted without any problem. Here you can find the complete code:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks = 0;
String qName = "";
ArrayList<String> answerList = new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
JavaScript example:
function toValue(field) {
return "integerValue" in field
? Number(field.integerValue)
: "doubleValue" in field
? Number(field.doubleValue)
: "arrayValue" in field
? field.arrayValue.values.map(toValue)
: "mapValue" in field
? toJSON(field.mapValue)
: Object.entries(field)[0][1];
}
function toJSON(doc) {
return Object.fromEntries(
Object.entries(doc.fields ?? {}).map(([key, field]) => [key, toValue(field)])
);
}
Related
I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)
This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 8 years ago.
i want to parse this json.i have difficulty when i try to parse the following json.suggest me proper way of parsing following json.i edit my code ,noe this is the correct code that i want to parse.
{
"tag":{
"tag1":1,
"tag2": "colour",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"Red",
"t2":"int",
"t3":1,
"t4":true
},
{
"t1":"Green",
"t2":"int",
"t3":2,
"t4":true
},
{
"t1":"Blue",
"t2":"int",
"t3":3,
"t4":true
}
],
"tag9":null,
"tag10":1
},
"tag":{
"tag1":2,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"value",
"t2":"value",
"t3":true,
"t4":true,
},
{
"t1":"value",
"t2":"value",
"t3":false,
"t4":true,
}
],
"tag9":1,
"tag10":3
},
"tag":{
"tag1":5,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":false,
"tag8": null,
"tag9":null,
"tag10":null
}
}
i had used this code
try {
JSONObject json= (JSONObject) new JSONTokener(loadJSONFromAsset()).nextValue();
JSONObject json2 = json.getJSONObject("tag");
for (int i = 0; i < json.length(); i++) {
int tag1 = (Integer) json2.get("tag1");
String tag2 = (String) json2.get("tag2");
String tag3 = (String) json2.get("tag3");
String tag4 = (String) json2.get("tag4");
int tag5 = (Integer) json2.get("tag5");
int tag6 = (Integer) json2.get("tag6");
boolean tag7 = json2.getBoolean("tag7");
if (!json2.isNull("tag8")) {
JSONArray jArray = json2.getJSONArray("tag8");
JSONObject json_data = null;
for (int i1 = 0; i1 < jArray.length(); i1++) {
json_data = jArray.getJSONObject(i1);
String Label = json_data.getString("t1");
String ValueType = json_data.getString("t2");
int Value = json_data.getInt("t3");
boolean isNextEnabled = json_data.getBoolean("t4");
}
}
int previous = 0;
if (!json2.isNull("tag9")) {
previous= (Integer) json2.get("tag9");
}
int next = 0;
if (!json2.isNull("tag10")) {
next = (Integer) json2.get("tag10");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("myjson");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
i get only last record ,how do i get all data .any help will be appreciated thanks...
You can try to parse your string # http://json.parser.online.fr/ it works nice for me.
From static review of the JSON string it seems you have "tag" element 3 times in your input and due to that parser might get confused. Try to remove duplicate entries and then try.
The JSONOject has a constructor that accepts a string of JSON data. You can use the constructor to parse the JSON string. If the string is valid JSON data, the constructor will return a JSONObject. If the string is NOT valid JSON, the constructor will throw an error. It's good practice to wrap the constructor inside of a try/catch block.
String json = "{name:\"value\"}";
JSONObject item = null;
try{
item = new JSONObject(json);
}catch(Exception exc){
Log.d(TAG, exc.toString());
}
if(item != null){
Log.d(TAG, String.format("name:%s", item.getString("name")));
}
I have tree JSON-structured data.
Something like
{
"result": [
{
"id": 1,
"name": "test1"
},
{
"id": 2,
"name": "test12",
"children": [
{
"id": 3,
"name": "test123",
"children": [
{
"id": 4,
"name": "test123"
}
]
}
]
}
]
}
model:
class DataEntity {
int id;
String name;
List<DataEntity> childDataEntity;
}
Parsing via org.json
List<DataEntity> categories = new ArrayList<DataEntity>();
private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
entity.setId(object.getInt("id"));
entity.setName(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
categories.add(entity);
}
}
return categories;
}
call
JSONObject jsonObject = new JSONObject(JSON);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
}
But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.
Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
ArrayList<DataEntity> finalResult = new ArrayList<>();
try {
JSONObject main = new JSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
DataEntity dataEntity = new DataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArray array = dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
DataEntity temp = parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObject object) throws JSONException {
categories.clear();
return recursivellyParse(entity, object);
}
Then call that from your loop.
How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.
I have JSON Response like this.I have tried a lot but unable to parse the Values.
{
"ResponseCode": "000",
"ResponseDescription": "Successful",
"SystemServiceID": [
"4"
],
"SystemServiceName": [
"Test Name"
],
"ProductID": [
"10"
],
"ProductName": [
"Testing"
],
"ProductDescription": [
"Test product"
],
"MinimumValue": [
10000
],
"MaximumValue": [
500000
],
"ImageURL": [
null
],
"Country": [
"Test"
],
"CompanyID": [
"1"
],
"CompanyName": [
"Test"
],
"FieldLevel": [
"2"
],
"FieldInfo": [
"{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"aaaaa\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}"
]
}
I have the last field FieldInfo which have the Field1,Field2 which comes dynamically from the server means sometimes FieldInfo have 2 Fields or Sometimes 3 Fields or Sometimes it have 4 fields and so on.
If it have the 2 Fields then it should be Field1,Field2
If it have the 3 Fields then it should be Field1,Field2,Field3 and so on.
Code
private ArrayList<BillPayProduct> parseBillPayResult(String data)
{
try
{
final JSONObject jsonObject=new JSONObject(data);
JSONArray jsonArray;
if(jsonObject.getString("ResponseCode").equals("000"))/*&&jsonObject.getString("ResponseDescription").equals("Successful"))*/
{
sysSerID=new ArrayList<String>();
sysSerName=new ArrayList<String>();
productID=new ArrayList<String>();
productName=new ArrayList<String>();
productDesc=new ArrayList<String>();
minVal=new ArrayList<String>();
maxVal=new ArrayList<String>();
ImageURL=new ArrayList<String>();
Country=new ArrayList<String>();
CompanyID=new ArrayList<String>();
CompanyName=new ArrayList<String>();
FieldLevel=new ArrayList<String>();
FieldInfo=new ArrayList<String>();
if(jsonObject.has("SystemServiceID"))
{
jsonArray=jsonObject.getJSONArray("SystemServiceID");
System.out.println("Length of systemserviceID:"+jsonArray.length()+"\ngetting System ServiceID");
for(int i=0;i<jsonArray.length();i++)
{
sysSerID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("SystemServiceName"))
{
jsonArray=jsonObject.getJSONArray("SystemServiceName");
System.out.println("Length of SystemServiceName:"+jsonArray.length()+"\ngetting System ServiceName");
for(int i=0;i<jsonArray.length();i++)
{
sysSerName.add(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductID"))
{
jsonArray=jsonObject.getJSONArray("ProductID");
System.out.println("Length of ProductID:"+jsonArray.length()+"\ngetting ProductID");
for(int i=0;i<jsonArray.length();i++)
{
productID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductDescription"))
{
jsonArray=jsonObject.getJSONArray("ProductDescription");
System.out.println("Length of ProductDescription:"+jsonArray.length()+"\ngetting ProductDescription");
for(int i=0;i<jsonArray.length();i++)
{
productDesc.add(jsonArray.getString(i));
}
}
if(jsonObject.has("BatchID"))
{
jsonArray = jsonObject.getJSONArray("BatchID");
System.out.println("length of BatchID:"+jsonArray.length()+"\nGetting BatchID");
for(int i=0;i<jsonArray.length();i++)
{
batchID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("MinimumValue"))
{
jsonArray = jsonObject.getJSONArray("MinimumValue");
System.out.println("length of MinimumValue:"+jsonArray.length()+"\nGetting MinimumValue");
for(int i=0;i<jsonArray.length();i++)
{
minVal.add(jsonArray.getString(i));
}
}
if(jsonObject.has("MaximumValue"))
{
jsonArray = jsonObject.getJSONArray("MaximumValue");
for(int i=0;i<jsonArray.length();i++)
{
maxVal.add(jsonArray.getString(i));
System.out.println(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductName"))
{
jsonArray=jsonObject.getJSONArray("ProductName");
System.out.println("length of productID:"+jsonArray.length()+"\nGetting product name");
for(int i=0;i<jsonArray.length();i++)
{
productName.add(jsonArray.getString(i));
}
}
/*if(jsonObject.has("ProductType"))
{
jsonArray=jsonObject.getJSONArray("ProductType");
System.out.println("length of productID:"+jsonArray.length()+"\nGetting product Type");
for(int i=0;i<jsonArray.length();i++)
{
productType.add(jsonArray.getString(i));
}
}*/
if(jsonObject.has("ImageURL"))
{
jsonArray=jsonObject.getJSONArray("ImageURL");
System.out.println("length of ImageURL:"+jsonArray.length()+"\nGetting ImageURL");
for(int i=0;i<jsonArray.length();i++)
{
ImageURL.add(jsonArray.getString(i));
}
}
if(jsonObject.has("Country"))
{
jsonArray=jsonObject.getJSONArray("Country");
System.out.println("length of ImageURL:"+jsonArray.length()+"\nGetting Country");
for(int i=0;i<jsonArray.length();i++)
{
Country.add(jsonArray.getString(i));
}
}
if(jsonObject.has("CompanyID"))
{
jsonArray=jsonObject.getJSONArray("CompanyID");
System.out.println("length of CompanyID:"+jsonArray.length()+"\nGetting CompanyID");
for(int i=0;i<jsonArray.length();i++)
{
CompanyID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("CompanyName"))
{
jsonArray=jsonObject.getJSONArray("CompanyName");
System.out.println("length of CompanyName:"+jsonArray.length()+"\nGetting CompanyName");
for(int i=0;i<jsonArray.length();i++)
{
CompanyName.add(jsonArray.getString(i));
}
}
if(jsonObject.has("FieldLevel"))
{
jsonArray=jsonObject.getJSONArray("FieldLevel");
System.out.println("length of FieldLevel:"+jsonArray.length()+"\nGetting FieldLevel");
for(int i=0;i<jsonArray.length();i++)
{
FieldLevel.add(jsonArray.getString(i));
}
}
if(jsonObject.has("FieldInfo"))
{
jsonArray=jsonObject.getJSONArray("FieldInfo");
System.out.println("length of FieldInfo:"+jsonArray.length()+"\nGetting FieldInfo");
for(int i=0;i<jsonArray.length();i++)
{
FieldInfo.add(jsonArray.getString(i));
}
}
ArrayList<BillPayProduct> BillPayproductList=new ArrayList<BillPayProduct>();
for(int i=0;i<productID.size();i++)
{
BillPayProduct billpay_products=new BillPayProduct();
billpay_products.setSystemServiceID((String)sysSerID.get(i));
billpay_products.setSystemServiceName((String)sysSerName.get(i));
billpay_products.setProductID((String)productID.get(i));
billpay_products.setProductName((String)productName.get(i));
billpay_products.setProductDesc((String)productDesc.get(i));
billpay_products.setMinValue((String)minVal.get(i));
billpay_products.setMaxValue((String)maxVal.get(i));
billpay_products.setImageURL((String)ImageURL.get(i));
billpay_products.setCountry((String)Country.get(i));
billpay_products.setCompanyID((String)CompanyID.get(i));
billpay_products.setCompanyName((String)CompanyName.get(i));
billpay_products.setFieldLevel((String)FieldLevel.get(i));
billpay_products.setFieldInfo((String)FieldInfo.get(i));
//inserting product into Database.
//inserting product into ArrayList
BillPayproductList.add(billpay_products);
}
return BillPayproductList;
}
}
catch (final JSONException e)
{
return null;
}
}
Bean Class
public class BillPayProduct extends Products
{
String Country;
String CompanyID;
String CompanyName;
String FieldLevel;
String FieldInfo;
public String getCountry()
{
return Country;
}
public void setCountry(String country)
{
Country = country;
}
public String getCompanyID()
{
return CompanyID;
}
public void setCompanyID(String companyID)
{
CompanyID = companyID;
}
public String getCompanyName()
{
return CompanyName;
}
public void setCompanyName(String companyName)
{
CompanyName = companyName;
}
public String getFieldLevel()
{
return FieldLevel;
}
public void setFieldLevel(String fieldLevel)
{
FieldLevel = fieldLevel;
}
public String getFieldInfo()
{
return FieldInfo;
}
public void setFieldInfo(String fieldInfo)
{
FieldInfo = fieldInfo;
}
}
My Question is that how can i check that how many fields it have???
And how to parse it and stored ?
What is the most preferable way to store the those values?
Any Help will be appreciated.
Thanks in Advance ... :)
you can enumerate the keys of the root, for instance
Iterator<String> keys = obj.keys();
What is the most preferable way to store the those values?
Tipically I create a read-only class, with the values I expect and I add it to a collection:
public class JSONDescriptor {
public final String filed1;
public final String filed2;
public JSONDescriptor(String filed1, String filed2) {
this.field1 = field1;
this.field2 = field2;
}
}
JSONObject jsonObject = new JSONObject(JSONResponse);
String mResponseCode = jsonObject.getString("ResponseCode");
String mResponseDescription = jsonObject.getString("ResponseDescription");
JSONArray jsonArray = jsonObject.getJSONArray("SystemServiceID");
Within this jsonArray you have only one value.If it's like that we can't able to parse the value.
So,it should be like this format"Id": "4"(which means object and it's value) within jsonArray.
Otherwise, if it takes only one id then change it to "SystemServiceID": "4"this format and it can be parsed as mRsespoonseCode parsing technique.
thanks dude. If you have any queries pls add comment.
Here is the exactly way to parse your JSON String :
JSONObject mMainObj = new JSONObject(mMyResult);
if(mMainObj != null){
String response = mMainObj.getString("ResponseCode"); // gets ResponseCode
String desc = mMainObj.getString("ResponseDescription"); //gets ResponseDescription
// SystemServiceID
JSONArray mSysService = mMainObj.getJSONArray("SystemServiceID");
if(mSysService != null){
for (int j = 0; j < mSysService.length(); j++) {
int mId = mSysService.getInt(j); // gets 4 and all other values, if there are some
}
}
// SystemServiceName
JSONArray mSysServiceName = mMainObj.getJSONArray("SystemServiceName");
if(mSysServiceName != null){
for (int j = 0; j < mSysServiceName.length(); j++) {
String mName = mSysServiceName.getString(j); // gets Test Name and all other values, if there are some
}
}
// The same for ProductID, ProductName and etc.
JSONArray mFieldInfo = mMainObj.getJSONArray("FieldInfo");
if(mFieldInfo != null){
for(int j = 0; j < mFieldInfo.length(); j++){
JSONObject mItem = mFieldInfo.getJSONObject(i);
if(mItem != null){
Iterator<Object> keys = mItem.keys();
while(keys.hasNext()){
String id = String.valueOf(keys.next()); // This value represent Field1
JSONArray mField = mItem.getJSONArray(id);
if(mField != null){
for(int i = 0; i < mField.length();i++){
JSONObject mElem = mField.getJSONObject(i);
if(mElem != null){
String mFieldName = mElem.getString("Field Name"); // value: Phone Number
// and etc.
}
}
}
}
}
}
}
}
Didn't tested the code, there can be some typo mistakes, if it's not working correctly just post a comment and I will fix it.
Hope this helps! : )