Get JSON String by iterating over array inside an object - java

Im working on an app where Im parsing JSON file and get the strings from it, but there is one String I have no idea why cant I get it into my activity.
the String is Object > Array > String
I have 2 activities and 1 model.
MainActivity: where Im parsing the JSON.
DetailActivity: where I need the String.
PostModel: a model where I have all setter and getter.
JSON:
{
"status":"ok",
"count":10,
"count_total":184,
"pages":19,
"posts":[
{ },
{
"id":2413,
,
"categories":[
{
"id":100,
"slug":"logging",
"title":"logging",
"description":"",
"parent":0,
"post_count":1
}
],
"comments":[
{
"id":3564,
"content":"<p>\u47 <\/p>\n",
"parent":0
}
],
"comment_count":1,
"thumbnail":"http:\/\/www.5.com\/wtent\g",
"custom_fields":{
"dsq_thread_id":[
"2365140"
],
"videoID":[
"--ffwf92jvDFy"
]
},
"thumbnail_images":{
"full":{
"url":"http:\/\/www.5.com\/jpg",
"width":727,
"height":454
},
"thumbnail":{
"url":"http:\/\/www.5.com\/wp-con50.jpg",
"width":150,
"height":150
}
}
}
]
}
PostModel:
private List<VidCast> videoIDList;
private String videoID;
public String getVideoID() {
return videoID;
}
public void setVideoID(String videoID) {
this.videoID = videoID;
}
public List<VidCast> getvideoIDList() { return videoIDList; }
public void setvideoIDList(List<VidCast> videoIDList) {
this.videoIDList = videoIDList;
}
public static class VidCast {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
MainActivity:
List<PostModel.VidCast> vidCasts = JsonPath.parse(URL_TO_HIT).read("$.posts.[*].custom_fields.[*].videoID[*]");
vidCasts = new ArrayList<>();
for (int s = 0 ; s < finalObject.getJSONArray("custom_fields").length() ; s++){
PostModel.VidCast vidCast = new PostModel.VidCast();
vidCast.setName(videoID);
vidCasts.add(vidCast);
}
postModel.setvideoIDList(vidCasts);
// adding the final object in the list
postModelList.add(postModel);
}
return postModelList;
}
}
DetailActivity:
StringBuffer stringBuffer = new StringBuffer();
for(PostModel.CategoryCast categoryCast : postModel.getCategoryCastList()){
stringBuffer.append(categoryCast.getName() + ", ");
}
StringBuffer videoStringBuffer = new StringBuffer();
for(PostModel.VidCast videoIDList : postModel.getvideoIDList()) {
videoStringBuffer.append(videoStringBuffer.toString());
}
At the last file is where I need to get the <> String. I spent a lot of time I just cant figure it out how I can iterate over array inside an object.
Thanks in advance!
__________update________
I managed to parse it that way :
JSONObject customFields = finalObject.getJSONObject("custom_fields");
JSONArray vidCastsJson = customFields.getJSONArray("videoID");
List<PostModel.VidCast> videoIds = new ArrayList<>();
for (int s = 0 ; s < vidCastsJson.length() ; s++){
PostModel.VidCast vidCast = new PostModel.VidCast();
vidCast.setName(vidCastsJson.optString(s));
videoIds.add(vidCast);
String videoID = String.valueOf(vidCastsJson);
vidCast.setName(videoID);
and I use Stringbuffer at DetailActivityStringBuffer
videoStringBuffer = new StringBuffer();
for(PostModel.VidCast vidCast : postModel.getvideoIDList()) {
videoStringBuffer.append(vidCast.getName());
String videoID = vidCast.toString();
}
But now I'm getting the videoID with the array brackets like that ["F3lyzrt"] I want it as a string to be only F3lyzrt, so I can pass it to my youtube player. Any advice will be appropriated.
Thanks,

It would look something like this:
JSONObject root = // however you get your root JSON object
JSONArray posts = root.optJSONArray("posts");
for(int i=0; i < posts.length(); i++){
JSONObject post = posts.optJSONObject(i);
int id = post.optInt("id");
JSONArray categories = post.optJSONArray("categories");
// etc.
}
Though you might want to consider using GSON or Jackson. With those libraries you can define a model to represent the data (jsonschema2pojo.org can help with that) and then it does all the parsing for you.
EDIT
You're not even trying to get the video id. Here's your code:
for (int s = 0; s < finalObject.getJSONArray("videoID").length(); s++){
{
postModel.setVideoID(videoID);
postModelList.add(postModel);
}
You see how you're not retrieving the contents of the json array?
JSONArray videoIds = finalObject.getJSONArray("videoID");
for (int s = 0; s < videoIds.length(); s++){
String videoID = videoIds.optString(s);
postModel.setVideoID(videoID);
postModelList.add(postModel);
}

Related

How to parse JSONArray which is in another JSONArray

I am trying to parse a JSONObject.
This JSONObject has a JSONArray in it, and it has another JSONArray inside of JSONArray.
The json form that I am trying to parse is as below.
{
"phone":"01029093199",
"store_id":"1",
"orders":[
{
"menu_id":"4",
"menu_defaultprice":"1500",
"extraorders":[
{
"extra_id":"1",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"38",
"extra_price":"300",
"extra_count":"2"
}
]
},
{
"menu_id":"4",
"menu_defaultprice":"1500",
"extraorders":[
{
"extra_id":"2",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"19",
"extra_price":"500",
"extra_count":"1"
}
]
},
{
"menu_id":"6",
"menu_defaultprice":"2000",
"extraorders":[
{
"extra_id":"6",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"21",
"extra_price":"500",
"extra_count":"1"
},
{
"extra_id":"41",
"extra_price":"300",
"extra_count":"1"
}
]
}
]
}
The code below is what I have tried before.
#RestController
public class OrderApiController {
private OrderService orderService;
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping("/OrderInsert.do")
public void insertOrder(#RequestBody JSONObject jsonObject) {
JSONParser jsonParser = new JSONParser();
System.out.println(jsonObject);
System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
System.out.println(jsonObject.get("store_id")); // store_id 가져오기 성공
System.out.println("==========JSONArray Parsing start=========");
ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
for(int i = 0; i < jsonArrayList.size(); i++) {
System.out.println(jsonArrayList.get(i)); // SUCCESS
String temp = jsonArrayList.get(i).toJSONString(); // WHERE ERROR HAPPENS
System.out.println(temp);
// Tried below code to remove "[", "]" from JSONArray, but not working.
// Error message was same as the message shown from line 37.
//String jsonString = temp.substring(1, temp.length()-1);
//System.out.println(jsonString);
// org.json.JSONObject jTemp = new org.json.JSONObject(jsonArrayList.get(i));
// System.out.println(jTemp); --> prints {} (empty JSONObject)
// System.out.println("menu_id : " + jTemp.getInt("menu_id")); // Not Working
}
}
}
The error shown is ..
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray
Additionally, I am using this json module dependency.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
I knew that if I print something on console using System.out.println(OBJECT), the OBJECT's toString()
method is called. So I tried to call toString() , and that gave me the ClassCastException exception.
Error is in fact at ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
Instead of casting JSONArray to ArrayList, you can traverse JSONArray and read its attributes. Your code can be changed something like.
#PostMapping("/OrderInsert.do")
public void insertOrder(#RequestBody JSONObject jsonObject) {
System.out.println(jsonObject);
System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
System.out.println(jsonObject.get("store_id")); // store_id 가져오기 성공
System.out.println("==========JSONArray Parsing start=========");
JSONArray orders = jsonObject.getJSONArray("orders");
for(int i = 0; i < orders.length(); i++) {
System.out.println(orders.get(i)); // SUCCESS
String temp = orders.get(i).toString();
System.out.println(temp);
// Travserse further json
JSONObject order = orders.getJSONObject(i);
System.out.println(order.get("menu_defaultprice"));
System.out.println(order.get("menu_id"));
JSONArray extraorders = order.getJSONArray("extraorders");
for(int j = 0; j < extraorders.length(); j++) {
JSONObject extraOrder = extraorders.getJSONObject(j);
System.out.println(extraOrder.get("extra_id"));
System.out.println(extraOrder.get("extra_price"));
System.out.println(extraOrder.get("extra_count"));
}
}
}
You are incorrectly fetching the orders. It should be stored in JSONArray, and NOT ArrayList
Replace:
ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
With:
JSONArray jsonArrayList = jsonObject.getJSONArray("orders");
Now, you can iterate JSONArray like this
for(int i = 0; i < jsonArrayList.length(); i++) {
System.out.println(jsonArrayList.get(i)); // SUCCESS
String temp = jsonArrayList.get(i).toJSONString();
System.out.println(temp);
}

jsonobject does not fully encapsulated a jsonarray or an arraylist when conveting

I am trying to sync contacts from the phone to the server using a sync adapter, when I retrieve a list of the contact from the phone and convert it into a jsonobject, the jsonobject does not fully encapsulated or contains the entire list. For example if the list size is 820 the jsonobject only contains 245 phone number and when I print out the jsonobject it does not have closing brackets, e.g {contacts :["07034355","0534535", just ends prematurely.
Please help me to find the solution.
1.Whats wrong
How to fix it.
if its an item within the list that does not match a json format how do I detect it
whats the best practice to sync contacts
Here is my code:
public void sync_contacts(Context context)
{
mContext=context;
mContentRevolver=context.getContentResolver();
phone.clear();
util = PhoneNumberUtil.getInstance();
String code=GetCountryZipCode();
Log.d(TAG,"COuntry ID:"+code);
if (mContentRevolver!=null){
phone=getAllContacts(mContentRevolver,code);
if (phone!=null){
String server_ip=mContext.getResources().getString(R.string.server_ip_url);
String file=mContext.getResources().getString(R.string.contact_sync);
String url=server_ip+file;
JSONArray jsonArray=new JSONArray(phone);
Log.d(TAG,"Array size"+jsonArray.length());
String arrayListPhone=jsonArray.toString();
Log.d(TAG,"Json Array to string"+arrayListPhone);
//Log.d(TAG,"Array size"+arrayListPhone);
// Log.d(TAG,"array list: "+arrayListPhone);
/* String phonenumber=PhoneNumber.getPhone();
if (phone!=null && url!=null){
Map<String,String> map=new HashMap<>();
map.put("phone",phonenumber);
map.put("contact_array",arrayListPhone);
send_data_via_volley(map, url, new Contact_Volley_CallBack() {
#Override
public void Respond(String respond) {
Log.d(TAG,"Respond: "+respond);
}
});
}*/
}
}
}
public String GetCountryZipCode(){
String[] countries=new String[3];
String CountryID="";
String CountryZipCode="";
String CountryName="";
TelephonyManager manager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
CountryID= manager.getSimCountryIso().toUpperCase();
String[] rl=mContext.getResources().getStringArray(R.array.CountryCodes);
for(int i=0;i<rl.length;i++){
String[] g=rl[i].split(",");
if(g[1].trim().equals(CountryID.trim())){
CountryZipCode=g[0];
break;
}
}
return CountryZipCode;
}
private void validate_phone(String number){
}
public ArrayList<String> getAllContacts(ContentResolver contentResolver,String country_code){
JSONObject jsonObject=new JSONObject();
JsonArray jsonArray=new JsonArray();
ArrayList<String> phone = new ArrayList<>();
String copywith0 = null;
Phonenumber.PhoneNumber number;
ContentResolver cR=contentResolver;
Cursor cursor=cR.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
if ((cursor!=null ? cursor.getCount() : 0)>0){
int i=0;
boolean isValid;
while (cursor!=null && cursor.moveToNext()){
String id=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))>0){
Cursor cursorPhone=cR.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",
new String[]{id},null);
while (cursorPhone.moveToNext()){
String s=cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
s=s.replace(" ","");
//s=s.replace("+","");
copywith0=s;
if (s.startsWith("0")) {
s = s.replaceFirst("0*","+"+country_code);
}
if (isValidMobileNumber(s)) {
s=s.replace("+","");
phone.add(convertStandardJSONString(s));
// phone.add(s);
// Log.d(TAG,"Phone: valide phone "+s);
}else {
//Log.d(TAG,"Phone: invalide phone "+copywith0);
if (copywith0.startsWith("0")){
// Log.d(TAG,"Phone: valide phone stating with 0 "+copywith0);
for (String r:util.getSupportedRegions()){
try {
if (util.isPossibleNumber(copywith0,r)){
number = util.parse(copywith0, r);
// check if it's a valid number for the given region
util.isValidNumberForRegion(number, r);
if (util.isValidNumberForRegion(number, r)){
copywith0=copywith0.replaceFirst("0*",String.valueOf(number.getCountryCode()));
if (isValidMobileNumber("+"+copywith0)){
// Log.d(TAG,"Phone: possible with after verification after vrified"+copywith0);
//jsonArray.add(s);
//phone.add(copywith0);
phone.add(convertStandardJSONString(copywith0));
}
}
}
}catch (NullPointerException e){}
catch (NumberParseException e) {
e.printStackTrace();
}
}
}
}
}
}
i++;
}
phone=Objects.requireNonNull(phone);
Log.d(TAG,"JSon:"+jsonArray.size());
phone.removeAll(Collections.singleton(null));
Set<String> hs = new HashSet<>();
hs.addAll(phone);
phone.clear();
phone.addAll(hs);
//Log.i(TAG, "NUmber of Contatcs: " + String.valueOf(i)+"\n"+"list size"+phone.size());
for (int y=0;y<phone.size();y++){
// Log.d(TAG,"Array_list: "+phone.get(y)+" json_list"+jsonArray.get(y)+"\n");
}
}
return phone;
}
public static boolean isValidMobileNumber(String phone) {
if (TextUtils.isEmpty(phone))
return false;
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
try {
Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
return phoneNumberType == PhoneNumberUtil.PhoneNumberType.MOBILE;
} catch (final Exception e) {
}
return false;
}
Here is the logcat result:
Array size828
2018-12-14 07:30:37.432 25029-26960/com.example.root.boda D/Contact_TAG: Json Array to
string["254741133082","254741133083","254741133084","254741133085","254724561852","254723682505","254772456998","254741133080","254741133081","254716550983","254700909017","254701389452","6785594462","6785594460","6785594461","254741133079","254708617549","254741133076","254741133077","254741133078","32468901349","254799302939","254710768069","32468901332","32468901330","6785594467","254704413355","254725967947","254719068000","6785594468","254701148467","6785594469","254705388507","254735730487","32468901336","32468901337","254707019734","254726044600","61404177647","6785594676","254710954360","23057911793","254725412223","254707485598","254728096111","37128909171","32468901368","254720671912","254729466494","254721808798","254721717621","6785999600","254716483828","254739497499","6785594451","254708753277","6785594450","254708617557","254722459845","254723235851","254741133042","254717109823","254723102063","254741133043","254741133044","254741133045","254741133041","61449015437","254728657128","254708345513","254713418008","6785594414","254726785139","254720610938","254702642030","254720700351","254723516105","254724284879","254724114910","254727102243","254727 456 557","32468901304","254755079071","254740117136","254755079072","254790624822","254791039378","254722619824","254740717332","254701499296","254704532914","254776992778","254792276498","254710978118","254790126098","254717898451","254704406898","254724030179","254791380500","32468901325","254737456860","254791845466","32468901323","254724467127","254720848120","254770888361","254714560079","254780945386","37255617788","254730124000","37123628890","254708489190","37123628892","37123628891","254714462609","254714229741","67570894108","32468901313","32468901314","254720893365","254724586752","254722931641","254701595752","254703656970","17672759447","254717668363","254714459498","254720601189","254790080382","254712651227","254702330880","254731725152","254720597028","93748502360","254725974637","254712192274","254725095347","254724239246","254731803976","967705210303","254717987521","254717521216","5493746288959","254706892333","61405284077","254701040949","254712045448","254709096000","254791369701","254733100111","254701639448","254713223971","254708824384","21698090036","254713787382","17672759451","254726115972","254709915000","25778675324","254729478260","254795082775","254703462246","254706615021","25778675321","254713657072","254722230305","254702744217","254703021000","254795713570","254703289327","254728086974","254727647973","254732282255","254707790892","254726256089","254720126752","254716100395","254710836007","254715406306","254718799745","254704358247","254720617963","254711523792","254792817272","254740460977","254714577345","254727073454","254707712615","254791042954","254796499114","254711429690","254706684678","254713105631","254737552981","254721138855","254711046999","254700093207","5493748502360","61414739233","254795155085","254727597083","254710809360","254710479200","254711218250","254716134905","61450735622","254706166227","254765199061","254711881085","254704986813","254701867730","254772254316","25729100928","41799775200","254717201134","32468931205","254716496588","254704628984","254724002456","41799775203","41799775202","41799775201","254720260881","61469350886","254700207664","254750100209","254750100208","254713244940","22569880964","254722427007","254700503258","254720223203","254721561357","254724333102","254701244396","254708851589","254710421253","254706313138","254755872755","254797508034","254790239559","254701145533","254726391889","254723042473","254708946935","254722293776","6768480002","254705317194","254780000348","61436025647","254711826273","254716551235","254790491413","254723491248","254751400262","254719316723","254721754455","254704099439","254786107568","254728678509","254715684243","41799775889","41799775888","41799775887","254716665372","254722896070","254792591160","254730692000","254707309337","254716460182","254714017442","254724636728","25470697967
Firstly, While printing the log messages in logcat, If the length of message is more than 1000 characters, it gets broken. Means you won't able to print the full message and it will be broke at some point.
So, If logcat is capping the length at 1000 then you can split the string you want to log with String.subString() and log it in pieces. For example:
public void logLargeString(String str) {
if(str.length() > 3000) {
Log.i(TAG, str.substring(0, 3000));
logLargeString(str.substring(3000));
} else {
Log.i(TAG, str); // continuation
}
}
Now you can able to print all the contacts data (828 contacts, it might be more than 1000 chars) with out any breaks. Then you can check the format of the output and parse the data accordingly.
JSONArray myarray = new JSONArray();
for (int i = 0; i < arrayList.size(); i++) {
myarray.put( arrayList.get( i ).getContactNumber() );
}
JSONObject contactsObj = new JSONObject();
studentsObj.put("contacts ", myarray );

JSONArray weird results

I was trying to get some information from a different class in java using JSONArrays and JSONObjects but for some reason I get very weird results.
My Info.java class I have:
public JSONArray getSpawnedPets() {
JSONArray petsArray = new JSONArray();
JSONObject petO = new JSONObject();
boolean spawned = false;
for (int i = 0; i <= 3; i++) {
spawned = true;
if (spawned) {
petO.put("petID", i);
petO.put("petOwner", "owner"+i);
petO.put("petName", "name");
petO.put("color", "s");
petO.put("particle", "s");
petsArray.add(petO);
}
}
return petsArray;
}
On my Main.java class I have:
public class main {
public static void main(String[] args) {
JSONArray petsArray = new JSONArray();
Info in = new Info();
petsArray = In.getSpawnedPets();
if (petsArray != null) {
for (int i = 0; i < petsArray.size(); i++) {
JSONObject po = (JSONObject) petsArray.get(i);
System.out.println("PetInfo:");
System.out.println(po.get("petID")+":");
System.out.println(""+po.get("petName"));
System.out.println(""+po.get("petOwner"));
}
}
}
}
The results were supposed to be increasing but yet I get this:
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
Did I do something wrong? I can't find my problem, the same code but not using classes works, but I have to use classes for it.
Cheers.
Create jsonobject in every iteration otherwise , there is only one JSONObject JSONObject petO = new JSONObject(); which is being updated in every iteration of loop
JSONArray petsArray = new JSONArray();
JSONObject petO;
//boolean spawned = false; // no need of it
for (int i = 0; i <= 3; i++) {
//spawned = true;
//if (spawned) { // no need of it , has no effect, always true
petO = new JSONObject();
// ^^^^^^^^^^^^^^^^^
petO.put("petID", i);
petO.put("petOwner", "owner"+i);
petO.put("petName", "name");
petO.put("color", "s");
petO.put("particle", "s");
petsArray.add(petO);
//}
}
Note : Since spawned is a local variable and will be set to true in first iteration and has no effect in code so there is no need of if

JSONArray cannot be converted to JSONObject exception

I have a JSON String structured in the following way and it throws an exception passing it into JSONArray timeJSONArray = new JSONArray(time);
This is the error Value [{"daysByte":158,"from":1020,"to":1260},{"daysByte":96,"from":1020,"to":1320}] at 0 of type org.json.JSONArray cannot be converted to JSONObject This is how I receive the array and I can't change it, so I'm having trouble converting it to a JSON Object instead of a JSON String which is the format it's currently in. What am I doing wrong?
[
[
{
"daysByte":30,
"from":660,
"to":1290
},
{
"daysByte":96,
"from":660,
"to":1320
},
{
"daysByte":128,
"from":1050,
"to":1290
}
],
[
{
"daysByte":252,
"from":690,
"to":840
},
{
"daysByte":252,
"from":1050,
"to":1260
}
]
]
This is the code I am working with. I'm getting the value passed in as a string
public ArrayList<String> getTimeList(String time){
System.out.println("PLACES ACTIVITY " + time);
ArrayList<String> times = new ArrayList<>();
try{
//JSONObject timeJSONObject = new JSONObject(time);
JSONArray timeJSONArray = new JSONArray(time);
ArrayList<LegacyTimeSpan> timeSpanList = new ArrayList<>();
LegacyTimeSpanConverterImpl converter = new LegacyTimeSpanConverterImpl();
for(int i = 0; i < timeJSONArray.length(); i++){
int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
int from = timeJSONArray.getJSONObject(i).getInt("from");
int to = timeJSONArray.getJSONObject(i).getInt("to");
System.out.println("TO " + to);
LegacyTimeSpan timeSpan = new LegacyTimeSpan(daysByte, from, to);
timeSpanList.add(timeSpan);
}
Log.d("Time span list", timeSpanList.toString());
WeekSpan weekSpan = converter.convertToWeekSpan(timeSpanList);
List<DayTimeSpanPair> dayTimeSpanPair = weekSpan.toDayTimeSpanPairs();
for(int i = 0; i< dayTimeSpanPair.size(); i++){
String timeRange = buildTimeString(dayTimeSpanPair.get(i));
times.add(timeRange);
}
} catch(JSONException e){
Log.d("PLACES EXCEPTION JSON",e.getMessage());
}
return times;
}
This Code should work i think as u declare the json Format.
[
[
{
} ,{},{} // Json Object Structure as u defined in you Question
topArray = ],
[
{
},{},{}
]
]
for(JSONArray objArray : topArray){
for(JSONObject eachObject : objArray){
System.out.println(eachObject.get("daysByte"););
System.out.println(eachObject.get("from");
System.out.println(eachObject.get("to");
}
}
Hi following code is working for your json I have tried. It is specific for your json not generic. so if you want you can use it.
try{
JSONArray jsonArray = new JSONArray(data); //insted "Data" pass your json Strint
for(int i=0 ; i<jsonArray.length() ; i++){
JSONArray internalArray = jsonArray.getJSONArray(i);
for(int j = 0 ; j < internalArray.length() ; j++){
JSONObject internalObject = internalArray.getJSONObject(j);
Log.d("data" , internalObject.getString("daysByte"));
Log.d("data" , internalObject.getString("from"));
Log.d("data" , internalObject.getString("to"));
}
}
}catch(Exception e){
Log.d("data" ,"Error");
}
}
You have two arrays, one array within other.
You have to do like this:
for(JSONArray temp: timeJsonArray)
{
// try to convert to json object
}
It is a 2D Array.
System.out.println("days");
String content = new Scanner(new File("C:/day.txt")).useDelimiter("\\Z").next();
Day[][] customDayWrap = new Gson().fromJson(content, Day[][].class);
for (Day[] days : customDayWrap) {
for (Day day : days) {
System.out.println(day.getDaysByte());
System.out.println(day.getFrom());
System.out.println(day.getTo());
}
}
And your Day Class will be something like this.
public class Day {
#SerializedName("daysByte")
#Expose
private Integer daysByte;
#SerializedName("from")
#Expose
private Integer from;
#SerializedName("to")
#Expose
private Integer to;
/**
*
* #return
* The daysByte
*/
public Integer getDaysByte() {
return daysByte;
}
/**
*
* #param daysByte
* The daysByte
*/
public void setDaysByte(Integer daysByte) {
this.daysByte = daysByte;
}
/**
*
* #return
* The from
*/
public Integer getFrom() {
return from;
}
/**
*
* #param from
* The from
*/
public void setFrom(Integer from) {
this.from = from;
}
/**
*
* #return
* The to
*/
public Integer getTo() {
return to;
}
/**
*
* #param to
* The to
*/
public void setTo(Integer to) {
this.to = to;
}
}
I tested this (I am using Google GSON library), and I was able to successfully read it.
Basically, there are two JSON arrays but you are accessing only one arrays that is why that error is shown
try {
JSONArray jsonArray = new JSONArray(a);
for (int j=0;j<jsonArray.length();j++) {
JSONArray timeJSONArray = jsonArray.getJSONArray(j);
for(int i = 0; i < timeJSONArray.length(); i++){
int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
int from = timeJSONArray.getJSONObject(i).getInt("from");
int to = timeJSONArray.getJSONObject(i).getInt("to");
System.out.println("TO " + to);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
After 1 hour of debugging your Json array I finally managed to figure out your actual issue. Its not only a Json Array its array inside the array.
So loop like this,
for (int i = 0; i < timeJSONArray.length(); i++) {
for(int j= 0;j<i;j++) {
int daysByte = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("daysByte");
int from = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("from");
int to = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("to");
Log.d("dataRecieved", "daybyte " + daysByte + "from " + from + "to " + to);
}
}
And do others as you need.

Parse the JSON String efficiently and in a clean way

In my below code, colData stores JSON String. Sample example for colData-
{"lv":[{"v":{"price":70.0,"userId":419},"cn":3},
{"v":{"price":149.99,"userId":419},"cn":3},
{"v":{"price":54.95,"userId":419},"cn":3}],
"lmd":20130206212543}
Now I am trying to match id value with userId value in the above JSON String. I am getting id value from a different source.
Meaning if id value is 419 then in the above JSON String userId value should also be 419. And in the JSON String, it might be possible there are lot of userId values so all the userId values should be matching with id. If any of them doesn't matches then log the exception.
So I was trying something like this-
final int id = generateRandomId(random);
for (String str : colData) {
if (!isJSONValid(str, id)) {
// log the exception here
LOG.error("Invalid JSON String " +str+ "with id" +id);
}
}
public boolean isJSONValid(final String str, final int id) {
boolean valid = false;
try {
final JSONObject obj = new JSONObject(str);
final JSONArray geodata = obj.getJSONArray("lv");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
JSONObject menu = person.getJSONObject("v");
if(menu.getInt("userId") == id) {
valid = true;
}
}
} catch (JSONException ex) {
valid = false;
}
return valid;
}
As per my understanding it looks like I can make isJSONValid method more cleaner. In my above isJSONValid method as I am repeating some stuff which I shouldn't be doing. Can anyone help me out how to make this more cleaner if I have missed anything. I will be able to learn some more stuff. Thanks for the help
You can initialize valid = true and set it to false when you find a non-valid userId and immediately fail:
public boolean isJSONValid(final String str, final int id) {
boolean valid = true;
try {
final JSONObject obj = new JSONObject(str);
final JSONArray geodata = obj.getJSONArray("lv");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
JSONObject menu = person.getJSONObject("v");
if(menu.getInt("userId") != id) {
valid = false;
break;
}
}
} catch (JSONException ex) {
valid = false;
}
return valid;
}
This way you iterate through all array's elements only if all are valid, which is the only case you actually have to.

Categories