JSON Parsing Error: Unexpected character (s) at position 226025 - java
I saw similar question on Stackoverflow but none of them helped me to solve my issue. So, I am asking for help as I have tried to find out what is the reason behind the error I am getting but failed. Please don't mark it as a duplicate question.
I am parsing a Json file and getting the following error.
Jun 06, 2017 2:06:24 PM edu.virginia.cs.services.FileManager ParseJson
SEVERE: null
Unexpected character (s) at position 226025.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:68)
at edu.virginia.cs.main.Processer.main(Processer.java:20)
Exception in thread "main" java.lang.NullPointerException
at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:76)
at edu.virginia.cs.main.Processer.main(Processer.java:20)
Code of interest:
try {
arr = (JSONArray) parser.parse(new FileReader(sourceFile));
} catch (IOException | ParseException ex) {
Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
}
File content looks like as follows:
[
{
"url": "http://www.save-on-crafts.com/",
"title": "Events & Wedding Sale | Save 20-60% | SaveOnCrafts",
"content": {
"p": ["Wedding decorations, party supplies, home d cor & craft supplies at 20-70% off. Save On Crafts brings you classic and trending fashions.", "Save On Crafts has continually evolved to meet the needs of our customers DIY brides, home decorators, party planners, florists, and caterers. Our goal is simple: provide an exciting selection of quality , , and items at the lowest price possible for the customer with discerning taste."],
"div": ["indicates required", "(831) 768-8428", "Take a Peek at our Specials: Save up to 70%!", "Candle Holders", "Flowers & Branches", "Crystal D cor, Chandeliers", "Set the Mood with Candles", "Champagne & Ice Buckets", "Chalkboards", "Eco Confetti", "Wedding Signs", "Sola Flowers", "Natural Wood Slices", "Classic & trending styles without the traditional retail markup.", "(831) 768-8428"],
"a": ["X", "What's New", "SPECIALS", "Wedding Decorations", "Lights | Event Lighting", "Wood Slabs & Tree Slices", "Vases", "Apothecary Jars", "Banners", "Baskets", "Bell Jars, Cloches", "Beverage Bar Supplies", "Bird Cages & Birds", "Botanicals, Lavender, Sola Flowers", "Bottles & Jars", "Branches - Natural", "Buckets & Tubs", "Burlap Fabric, Jute, and Linen", "Cake Stands", "Candles", "Candle Holders", "Candy Buffet", "Chair Sashes, Banners, Signs", "Chalkboards", "Chandeliers", "Charger & Base Plates", "Confetti", "Corsage & Bouquet Supplies", "Craft Supplies", "Crates, Boxes, & Trays", "Crystal Decorations", "Easels & Frames", "Event Decor", "Favors", "Feathers", "Floral Supplies", "Flowers", "Greenery", "Home & Garden Decor", "Lanterns", "Mirrors & Mirror Stands", "Moss Natural & Artificial", "Nautical Decor & Decorations", "Packaging, Gift Wrapping", "Paper Lanterns & Parasols", "Paper Party Decorations", "Party Supplies", "Pots & Planters", "Placecard Holders,Table Numbers, Displays", "Preserved Flowers & Leaves", "Props, Pedestals, Risers", "Ribbon", "Silk Flowers", "Signage", "Shells - Sand", "Shepherds Hooks & Stanchions", "Sola Flowers", "Succulents & Cactus", "Table Runners & Toppers", "Terrariums", "Tote Bags, Welcome Bags", "Trees, Potted Plants", "Vases & Vase Fillers", "Wedding Cake Decorations and Toppers", "Wedding Decorations", "Wedding Signs", "Wedding Themes", "Wedding Trees & Wishing Trees", "Wood Crafts", "Wood Slabs & Tree Slices", "Wreath Making Supplies, Frames, Forms", "Gifts - Holiday Decorations", "Gifts Under $25", "Ideas & Inspiration", "Shopping Cart", "About", "Shipping", "Return Policy", "Contact", "FAQ", "Privacy Policy", "Terms and Conditions", "Read More", "Shipping", "Cart"],
"strong": ["Need Help?", "SUBSCRIBE", "wedding supplies", "party decorations", "home d cor", "Affordable Wedding & Event Decor", "Save 20-70%", "Need Help?"],
"span": ["*", "*", "Live Chat", "Shop Categories", "Customer Service: 7am - 5pm PST (M-F) | (831)768-8428", "Copyright 2017 Save-On-Crafts. All Rights Reserved. Designated trademarks and brands are the property of their respective owners. Use of this website constitutes acceptance of the Save-On-Craftsand Privacy Policy.", "Live Chat"]
}
},
{
"url": "http://www.carsurvey.org/",
"title": "Carsurvey.org - Car Reviews",
"content": {
"p": ["I feel as if this vehicle was custom built for me, love it", "Neat cruiser, comfort first, performance second", "Beast maaaaaaate!", "Best value for the money", "There are reviews on the site", "new reviews and new comments are in the Members section, awaiting approval"],
"td": ["2 days ago", "2 days ago", "3 days ago", "3 days ago", "18 hours ago", "19 hours ago", "19 hours ago", "19 hours ago"],
"a": ["Write a Review", "About", "Members", "Reviews by Region", "Write a Review", "About", "Members", "Reviews by Region", "BMW", "Buick", "Chevrolet", "Chrysler", "Citroen", "Dodge", "Fiat", "Ford", "Honda", "Hyundai", "Jeep", "Kia", "Mazda", "Mercedes-Benz", "Mercury", "Mitsubishi", "Nissan", "Oldsmobile", "Peugeot", "Pontiac", "Renault", "Saturn", "Subaru", "Toyota", "Vauxhall", "Volkswagen", "Volvo", "AC", "Acura", "Alfa Romeo", "Alvis", "AMC", "ARO", "Asia Motors", "Aston Martin", "Asuna", "Audi", "Austin", "Austin Healey", "Autobianchi", "Autocars", "Avanti", "Bajaj", "Bedford", "Bentley", "Birkin", "BMW", "Bombardier", "Bond", "Brennan-Mays", "Bricklin", "Bugatti", "Buick", "Cadillac", "Caterham", "Checker", "Chery", "Chevrolet", "Chrysler", "Citroen", "Commer", "Cord", "Dacia", "Daewoo", "DAF", "Daihatsu", "Datsun", "DeLorean", "DeSoto", "DeTomaso", "Dodge", "Eagle", "Edsel", "Ferrari", "Fiat", "Ford", "Franklin", "Freightliner", "FSO", "Geely", "Geo", "GMC", "Great Wall", "Grinnall", "Hillman", "Holden", "Honda", "HSV", "Humber", "Hummer", "Hyundai", "IHC", "IKA", "Infiniti", "Innocenti", "Inokom", "Iran Khodro", "Iso Rivolta", "Isuzu", "Iveco", "Jaguar", "Jeep", "Jensen", "JiangNan", "Kaiser", "Kia", "Kish Khodro", "Lada", "Laforza", "Lamborghini", "Lancia", "Land Rover", "Lexus", "Leyland", "Leyland DAF", "Lincoln", "Lotus", "Mahindra", "Maple", "Marcos", "Maruti", "Maserati", "Matra", "Maybach", "Mazda", "McLaren", "Mercedes-Benz", "Mercury", "Merkur", "Meson", "Meyers Manx", "MG", "Microcar", "Mitsubishi", "Morgan", "Morris", "Moskvitch", "Nash", "NAZA", "Nissan", "Noble", "Nova", "NSU", "Oldsmobile", "Oltcit", "Opel", "Packard", "Panther", "Perodua", "Peugeot", "Plymouth", "Pontiac", "Porsche", "Premier", "Proton", "Puma", "Pyonghwa Motors", "Quantum", "Qvale", "Ram Trucks", "Rayton Fissore", "Reliant", "Renault", "Riley", "Robert Jankel Design", "Rolls Royce", "Rover - Austin", "SAAB", "Saleen", "Samsung", "Santana", "Sao", "Saturn", "Scion", "Seat", "Sebring", "Sebring Vanguard", "Shelby", "Simca", "Singer", "Skoda", "smart", "Spartan", "SsangYong", "Standard", "Sterling", "Studebaker", "Subaru", "Sunbeam", "Suzuki", "Talbot", "Tata", "Tatra", "Tesla", "Tickford", "Toyota", "Trabant", "Triumph", "Troller", "TVR", "Vanden Plas", "Vauxhall", "Venturi", "Volga", "Volkswagen", "Volvo", "Wartburg", "Westfield", "Willys", "Wolseley", "Yugo", "Zagato", "ZAZ", "Zhengzhou Nissan", "Zhonghua", "ZXAUTO", "1997 Lexus LS", "2012 Audi A7", "1985 Dodge D100", "2007 Citroen C5", "More New Car Reviews", "1987 Chrysler New Yorker", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "More New Comments", "Advertise on this site", "Privacy Policy"],
"strong": ["110091", "0", "3"],
"h1": ["Car Reviews by Manufacturer"],
"h2": ["Most Popular", "All Manufacturers"],
"h3": ["Newest Car Reviews", "Newest Comments", "Current Status"],
"span": ["Copyright 1997 - 2017 CSDO Media Limited", "|"]
}
},
{
"url": "http://www.hollywood.com/",
"title": "Hollywood.com - Best of Movies, TV, and Celebrities",
"content": {
"div": ["TRENDING NOW", "Hollywood.com Photo Archive", "Hollywood.com Esports", "Hollywood.com Discovery", "MovieTickets.com Discovery", "Wenn Penelope Cruz will always put her all into every role she wins, even if it means transforming herself physically. The Spanish actress has varied...", "Wenn Sean Penn reportedly resolved a dispute with fellow passengers during a recent flight to New York. The Mystic River actor had just boarded the...", "Wenn Rita Ora has hinted in a new interview that she and Cara Delevingne were more than just good friends. The 26-year-old singer and the...", "Wenn Charlie Sheen has stepped out in public with a new girlfriend. The 51-year-old actor showed off his blonde partner, known only as Jools, as...", "Wenn Tom Cruise's insistence on perfecting a zero-gravity stunt for The Mummy caused members of the film's crew to vomit. Tom stars as military operative...", "Wenn The Big Chill star Meg Tilly has made a return to Hollywood after 18 years to play Brad Pitt's wife. The actress stepped away...", "Wenn Rob Kardashian has slammed rumors he's dating reality TV star Mehgan James. A report published by Us Weekly magazine on Thursday (01Jun17) suggested that...", "Wenn Taylor Swift has been pictured with her actor boyfriend Joe Alwyn for the first time. News of the Bad Blood hitmaker's relationship with 26-year-old...", "NBC Ariana Grande has touched down in the U.K. ahead of her benefit concert for victims of the terrorist attack on her gig in...", "Wenn Alec Baldwin helped raise $5.1 million for New Jersey Democrats at an event in Collingswood, New Jersey, on Thursday night (01Jun17). The 30 Rock...", "Wenn Johnny Depp has claimed he was completely unaware his former managers were using his name to take out $40 million in loans. The fight...", "Wenn Carey Mulligan is reportedly expecting her second child. The Great Gatsby actress was pictured outside Sexy Fish restaurant in London with her husband Marcus...", "When it was first announced that Scarlett Johansson would play The Major in the wildly popular 'Ghost in the Shell' fans weren't happy, to...", "Billy Bob Thornton and the cast of Bad Santa 2 looked super naughty at AMC Loews Lincoln Square in New York City. Check out...", "Hulu's much anticipated drama The Handmaid's Tale premiered last night. This 10-part series is an adaptation from Margaret Atwood's 1985 novel of the same name, set...", "Julianne Moore and Michelle Williams premiered their new movie Wonderstruck at the 70th Cannes Film Festival. For a complete gallery of pictures, click here.", "Selena Gomez hosted WE Day celebrations at The Forum in California for her fifth year. WE Day is one of the largest Facebook non-profits in...", "Check out the super whimsical cast of NBC's Hairspray Live! before the musical premieres Wednesday, December 7th!", "Wenn / Paramount Pictures Thandie Newton wore a wig she was given on Mission: Impossible 2 to the BAFTAs on Sunday night (12Feb17). The Westworld...", "The Light Between Oceans premiered at the Venice Film Festival and co-stars and real-life lovers Michael Fassbender and Alicia Vikander were all smiles on...", "With the Margot Robbie stepping into the role of Maid Marian, and the currently-filming of Robin Hood: Origins, there's been a resurgence of interest...", "Tom Hanks is Forrest Gump, just like like Richard Gere is Edward Lewis in Pretty Woman; some actors have had such iconic movie roles,...", "Disney These days, Disney is known for pushing the envelope and hiding adult themes and jokes in their films. However, there was a time...", "ABC Television Network Abby, The Deadliest Catch Darby Stanchfield plays Abby Whelan, and she's come a long way to get to D.C. She actually grew up...", "There are many different kinds of family businesses, but one we hardly think about is acting. However, there are families that have actors going...", "It's no secret that Hollywood loves its cliches from action heroes who magically avoid every bullet fired at them to fat sitcom husbands who...", "HBO HBO's Silicon Valley just finished its first season. The show features a great cast of comedians, and it's managed to satirize the nerdy masculinity of...", "32.2x", "|", "19.2x", "|", "6.84x", "|", "6.16x", "|", "4.77x", "|", "4.22x", "|", "Powered by Crowdtangle", "1999-2017 HOLLYWOOD.COM, LLC. ALL RIGHTS RESERVED", "| | | |", "MOVIE, TV, AND CELEBRITY DATA PROVIDED BY AND IS THE COPYRIGHT OF"],
"a": ["CLOSE", "Click here - to use the wp menu builder", "Click here - to use the wp menu builder", "SIGN UP FOR OUR NEWSLETTER", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "Kathy Griffin in Tears at Press Conference", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "Sean Penn Involved in Dispute During Flight to JFK", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "'Baby Driver' Looks Like The Most Fun Movie In 2nd Trailer", "Go Behind the Voices of 'Captain Underpants: The First Movie'", "Something Is Wrong In the 'Murder on the Orient Express' Trailer", "Nicole Kidman lends her Balenciaga wedding dress to exhibition", "Penelope Cruz: I don t mind getting ugly for movie roles", "Sean Penn Involved in Dispute During Flight to JFK", "Rita Ora talks ambiguous relationship with Cara Delevingne", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt s Wife", "Rob Kardashian Denies Reports He s Dating Reality Star Mehgan James", "Taylor Swift Spotted with New Boyfriend Joe Alwyn for First Time", "Ariana Grande returns to U.K. as thousands make false ticket claims for Manchester benefit show", "Alec Baldwin Raises $5 million for Democrats", "Johnny Depp was unaware ex managers were using his name to get loans", "Carey Mulligan is Pregnant", "see more", "RED CARPET", "Travel To Tokyo For The Ghost in the Shell World Premiere", "The Cast Of Bad Santa 2 Spiced Up The Red Carpet At The NYC Premiere", "Hulu s The Handmaid s Tale Premieres", "Julianne Moore and Michelle Williams Premiere Wonderstruck at Cannes", "Selena Gomez, Demi Lovato, and Alicia Keys Celebrate WE Day", "The Cast Of NBC s Hairspray Live! Were Super Whimsical On The Red Carpet", "Thandie Newton wore Mission: Impossible II wig to the BAFTAs", "Michael Fassbender & Alicia Vikander Are Perfection At The Light Between Oceans Premiere", "see more", "DID YOU KNOW?", "All the Actresses Who Have Played Maid Marian", "12 Iconic Movie Roles That Famous Actors Turned Down", "The Original Drawing For Snow White Was Banned By Disney Because It Was Too Sexy!", "Facts You Never Knew About The Cast of Scandal", "11 Actors You Didn t Know Have Famous Grandparents", "15 Celebrity Dads You Didn t Know Have Hot Sons", "The 10 Most Overused Sound Effects in Hollywood", "21 Facts You Don t Know About Silicon Valley", "see more", "Teen Mom: OG Star Ryan Edwards Has Checked into Rehab", "E! News", "How To Train Your Dragon 3: Eveything We Know So Far", "moviepilot.com", "Alec Baldwin's Advice to Kathy Griffin on Trump Brouhaha: 'F--- Them All'", "The Wrap", "Alec Baldwin Defends Kathy Griffin in Wake of Trump Decapitated Photo Controversy: 'Ignore Him'", "People", "The Wonder Woman Scene That Pays Tribute To Superman", "CinemaBlend", "14 Of The Most Utterly Bizarre Things On Display At The M tter Museum", "Ranker", "Movies", "TV", "Celebrities", "Best Of/Worst Of", "Where Are They Now?", "Did You Know", "Buzzing", "Quizzes", "Pop Lists", "News", "SSNInsider", "MovieTickets.com", "EsportsHW", "Photo Archive", "About Us", "Contact Us", "Media Kit", "PRIVACY POLICY", "TERMS OF SERVICE", "COPYRIGHT ISSUES", "DISCLOSURE", "REPORT ABUSE", "BASELINE"],
"em": ["Want More?"],
"h1": ["WANT MORE?"],
"i": ["Facebook", "Google+", "Twitter", "YouTube", "Instagram"],
"h2": ["Sign Up For Our Newsletter!", "Sign Up For Our Newsletter!"],
"h3": ["FOLLOW US!", "LIKE US!", "TOPIC", "Category", "partners", "COMPANY", "Be friends with us"],
"time": ["Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Mar 17, 2017", "Nov 16, 2016", "Apr 26, 2017", "May 18, 2017", "Apr 28, 2017", "Nov 18, 2016", "Feb 14, 2017", "Sep 1, 2016", "Mar 7, 2017", "Aug 15, 2013", "Oct 5, 2016", "Apr 4, 2014", "Apr 22, 2016", "Aug 22, 2014", "Sep 21, 2015", "Jun 11, 2014"],
"span": ["Celebrities", "Movies", "Television", "Showtimes", "Search", "Esports", "Photo Archive", "The Latest", "Video", "Buzzing", "Pop Lists", "Did You Know?", "Where Are They Now?", "Featured", "Take A Sneak Peak At The Movies Coming Out This Week (8/12)", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The Captain Underpants Premiere", "Khloe Kardashian won t identify friend she claims is stealing from her", "Penelope Cruz: I don t mind getting ugly for movie roles", "Partners", "MovieTickets.com", "SSN Insider", "Privacy Policy", "Copyright Notice", "Terms of Use", "Report Abuse", "Videos", "Buzzing", "Red Carpet", "Esports", "Photo Archive", "Newsletter Signup", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "WENN", "Kathy Griffin in Tears at Press Conference", "WENN", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "WENN", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "WENN", "Sean Penn Involved in Dispute During Flight to JFK", "WENN", "Khloe Kardashian won't identify friend she claims is stealing from her", "WENN", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Michael Chaney", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "WENN", "Charlie Sheen goes public with new girlfriend", "WENN", "Sign Up for Our Newsletter!", "Follow #hollywood", "THE LATEST", "Hot on Facebook"]
}
}
]
I have crawled 500K webpages and stored them in a Json file. Now, I am trying to read it. The whole file is 2GB, so I am unable to share the whole file.
I understand Json parser is getting some unexpected character (s) in the file but I am unable to find which line in the json file is erroneous. Is there any way I can find out the faulty line in the json file?
Edit
Main code in processing webpage contents is as follows.
for (Element element : elements) {
String tagName = element.tagName();
if (Util.isValidTag(tagName)) {
String textValue = Util.removeNonPrintableChars(element.ownText()).trim().replace("\"", "\'");
if (!textValue.isEmpty()) {
if (tagTextMap.containsKey(tagName)) {
tagTextMap.get(tagName).add(textValue);
} else {
ArrayList<String> arr = new ArrayList<>();
arr.add(textValue);
tagTextMap.put(tagName, arr);
}
}
}
}
I just removed non-printable characters and also replace double quotes by single quote, that's it.
Update
I found the problematic section in the json file.
{
"url": "http://www.kudzu.com/",
"title": "Atlanta roofers, hvac, plumbers, electricians and other businesses - reviews, coupons and cost estimates from your neighbors.",
"content": {
"h2": ["From Our Experts", "Recent Projects", "Recent Articles", "What It Costs", "Review a Business", "What It Costs", "Other Markets"],
"body": ["\"],
"span": ["Area", "Area", "Cost"]
}
}
This part - "body": ["\"], is the source of problem. I can understand now why its causing the problem.
It seems you are having trouble with escaping special characters. See this list of special characters used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\ Backslash character
So, while dumping json you need to escape this special characters. Fortunately every json library's has way to do this job. As it seems you have used JSON.simple toolkit, you can use JSONObject.escape() method to escape the special characters.
I also faced same issue
Unexpected character (s) at position 226025.
While reading json file using code, which is mention below :
JSONParser jsonparser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject)jsonparser.parse("filepath");
System.out.println((String) jsonObj.get("id"));
}
catch(Exception e) {
e.printStackTrace();
}
Then I simply updated my code using fileReader Object in my code, it worked:
JSONParser jsonparser = new JSONParser();
try {
JSONObject jsonObj = (JSONObject)jsonparser.parse(new FileReader("filepath"));
System.out.println((String) jsonObj.get("id"));
}
catch(Exception e) {
e.printStackTrace();
}
Related
First item in ListView from Adapter is missing some constraints
Having an issue that popped up recently with seemingly no change to my code. With a list of news that's fetched, the first item in the list always has broken constraints. The template is a vertical linear layout, that has the title, and a constraint layout under that with the image, description, source, and time of the article. The information gets placed into the template via a custom adapter class, which nothing has changed in since the issue started. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="#+id/layNewsBackground" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="7" android:background="#color/colorDarkSurface1dp" android:baselineAligned="false" android:descendantFocusability="blocksDescendants" android:gravity="center_vertical" android:orientation="vertical" android:padding="8dp"> <TextView android:id="#+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="6dp" android:ellipsize="end" android:fontFamily="#font/source_sans_pro" android:maxLines="1" android:scrollHorizontally="true" android:textAlignment="viewStart" android:textSize="17sp" android:textStyle="bold" tools:text="This is the news title" /> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical"> <androidx.cardview.widget.CardView android:id="#+id/cardView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:cardBackgroundColor="#android:color/transparent" app:cardCornerRadius="4dp" app:cardElevation="0dp" app:cardPreventCornerOverlap="false" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <ImageView android:id="#+id/galleryImage" android:layout_width="70dp" android:layout_height="70dp" android:contentDescription="TODO" /> </androidx.cardview.widget.CardView> <TextView android:id="#+id/sdetails" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:ellipsize="end" android:fontFamily="#font/source_sans_pro" android:maxLines="2" android:minLines="2" android:textSize="16sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="#+id/cardView" app:layout_constraintTop_toTopOf="parent" tools:text="Description" /> <TextView android:id="#+id/source" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:fontFamily="#font/source_sans_pro" android:textSize="15sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="#+id/cardView" tools:text="Source" /> <TextView android:id="#+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="#font/source_sans_pro" android:textSize="14sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" tools:text="Time" /> </androidx.constraintlayout.widget.ConstraintLayout> </LinearLayout> { "status": "ok", "totalResults": 41, "articles": [ { "source": { "id": "cnn", "name": "CNN" }, "author": "Brian Fung, CNN Business", "title": "It's never been easier to start a social network. Succeeding is another story", "description": "So what does it take to launch a successful social platform in the year 2021? The answer is part technical and part strategy, and the breakdown between the two reflects how dramatically different the challenges are for new entrepreneurs compared to the days o…", "url": "https://www.cnn.com/2021/04/08/tech/social-media-startups/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210406133012-clubhouse-social-media-startups---stock-super-tease.jpg", "publishedAt": "2021-04-08T13:55:39Z", "content": "(CNN Business)Former President Donald Trump lost his most-prized megaphone when he was suspended from Facebook and Twitter earlier this year. Since then, he's largely stuck with canned press statemen… [+7456 chars]" }, { "source": { "id": "the-globe-and-mail", "name": "The Globe And Mail" }, "author": "Stephen Nellis", "title": "Apple will argue it faces competition in video game transaction market in Epic lawsuit - The Globe and Mail", "description": "The dispute arose after Epic tried to implement its own in-app payment system in the popular Fortnite game and Apple subsequently banned the game from its App Store", "url": "https://www.theglobeandmail.com/business/technology/article-apple-will-argue-it-faces-competition-in-video-game-transaction-market/", "urlToImage": "https://www.theglobeandmail.com/resizer/fWGZOwQ8InxKixRf7H_p8rDAn2Y=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/6PBYASTO75J4VLBKZ4THZYACXU.JPG", "publishedAt": "2021-04-08T10:41:56Z", "content": "Apple Inc said it plans to argue that it faces abundant competition in the market for video game transactions to defend itself against antitrust allegations by Fortnite maker Epic Games, the iPhone m… [+2022 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Theresa Waldrop, CNN", "title": "There's a lot of debate about vaccine passports right now. What are they, and how would they work?", "description": "With millions of Americans being vaccinated against Covid-19 every day, a heated debate is underway -- do these people need proof of immunization in the form of a vaccine passport?", "url": "https://www.cnn.com/2021/04/07/us/covid-vaccine-passport-explainer/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324154815-02-new-york-excelsior-pass-ibm-super-tease.jpg", "publishedAt": "2021-04-08T01:59:40Z", "content": "(CNN)With millions of Americans being vaccinated against Covid-19 every day, a heated debate is underway -- do these people need proof of immunization in the form of a vaccine passport?\r\nJust like a … [+5359 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Clare Duffy, CNN Business", "title": "Fintech firm Plaid announces $425 million funding round", "description": "Financial technology firm Plaid on Wednesday announced a $425 million Series D funding round, more than doubling the total amount the company has raised since its 2012 founding.", "url": "https://www.cnn.com/2021/04/07/tech/plaid-funding-425-million/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210406201158-zach-perret-jan-2020-super-tease.jpg", "publishedAt": "2021-04-07T11:00:04Z", "content": "New York (CNN Business)Financial technology firm Plaid on Wednesday announced a $425 million Series D funding round, more than doubling the total amount the company has raised since its 2012 founding… [+2928 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Matt Villano, CNN", "title": "World Autism Awareness Day 2021: What you need to know", "description": "World Autism Awareness Day, which is April 2, encourages awareness about the existence of autism and the roughly 4 million autistic individuals around the world.", "url": "https://www.cnn.com/2021/04/02/health/autism-awareness-day-wellness/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210401142347-autism-awareness-wellness-super-tease.jpg", "publishedAt": "2021-04-02T11:24:15Z", "content": "(CNN)In many ways, Kevin \"Knox\" Johnson III is just like most 8-year-olds.\r\nThe kid enjoys building marble runs. He's obsessed with knock-knock jokes. In school, he excels at math and learning langua… [+8788 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Zachary Cohen, Alex Marquardt and Geneva Sands, CNN", "title": "Hunting the hunters: How Russian hackers targeted US cyber first responders in SolarWinds breach", "description": "After infiltrating US government computer networks early last year as part of the SolarWinds data breach, Russian hackers then turned their attention to the very people whose job was to track them down.", "url": "https://www.cnn.com/2021/04/02/politics/russian-hackers-target-us-cyber-hunters-solarwinds/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/181217084838-20181217-russia-social-media-super-tease.jpg", "publishedAt": "2021-04-02T10:00:10Z", "content": "Washington (CNN)After infiltrating US government computer networks early last year as part of the SolarWinds data breach, Russian hackers then turned their attention to the very people whose job was … [+7658 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "By Michael Andronico, Jason Cipriani and Jacob Krol, CNN", "title": "The best laptops of 2021", "description": "We spent months testing the latest and greatest laptops we could get our hands on, from Apple to Dell to Microsoft to Lenovo, and we've found the best options for any of your needs.", "url": "https://www.cnn.com/2021/04/01/cnn-underscored/best-laptops/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/201207080817-best-laptops-lead-december-lead-super-169.jpg", "publishedAt": "2021-04-01T17:27:02Z", "content": "Buying a new laptop is both an exciting and potentially frustrating experience. Exciting, of course, because a powerful computer that allows you to communicate and work efficiently and keep yourself … [+28140 chars]" }, { "source": { "id": "cbc-news", "name": "CBC News" }, "author": "Isabelle Leger", "title": "Controversial candidate for Saint John mayor says he can relate to people", "description": "A candidate for mayor of Saint John whose Facebook postings have included support for conspiracy theories and the January attack on the U.S. Capitol says the city needs a leader who doesn't fit the status quo.", "url": "https://www.cbc.ca/news/canada/new-brunswick/darrell-bastarache-saint-john-mayor-1.5971169", "urlToImage": "https://i.cbc.ca/1.5971442.1617213053!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/darrell-bastarache.jpg", "publishedAt": "2021-03-31T20:33:50Z", "content": "A candidate for mayor of Saint John whose Facebook postings have included support for conspiracy theories and the January attack on the U.S. Capitol says the city needs a leader who doesn't fit the s… [+2142 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Rishi Iyengar, CNN Business", "title": "Silicon Valley is starting to bring workers back to the office", "description": "After years of building huge modern offices and a work culture that many industries have emulated, Silicon Valley was among the first to shutter those offices and go fully remote when the coronavirus pandemic began.", "url": "https://www.cnn.com/2021/03/31/tech/silicon-valley-office-return-uber-facebook/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210329184012-uber-mission-bay-file-restricted-super-tease.jpg", "publishedAt": "2021-03-31T11:54:33Z", "content": "San Francisco (CNN Business)After years of building huge modern offices and a work culture that many industries have emulated, Silicon Valley was among the first to shutter those offices and go fully… [+5899 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Rishi Iyengar and Jon Sarlin, CNN Business", "title": "NFTs are suddenly everywhere, but they have some big problems", "description": "For several weeks, it's been near impossible to exist on the internet without at least hearing a mention of NFTs. Short for non-fungible tokens, they are pieces of digital content linked to the blockchain, the digital database underpinning cryptocurrencies su…", "url": "https://www.cnn.com/2021/03/30/tech/nft-hacking-theft-environment-concerns/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210326185518-03-nft-non-fungible-tokens---stock-super-tease.jpg", "publishedAt": "2021-03-30T19:17:42Z", "content": "(CNN Business)For several weeks, it's been near impossible to exist on the internet without at least hearing a mention of NFTs. Short for non-fungible tokens, they are pieces of digital content linke… [+8408 chars]" }, { "source": { "id": "cbc-news", "name": "CBC News" }, "author": "Alan Suderman", "title": "Russian hackers found to have accessed email of U.S. Homeland Security head, cybersecurity staff", "description": "Suspected Russian hackers gained access to email accounts belonging to the Trump administration's head of the U.S. Department of Homeland Security and members of the department's cybersecurity staff whose jobs included hunting threats from foreign countries, …", "url": "https://www.cbc.ca/news/world/russian-hack-solarwinds-us-government-1.5968734", "urlToImage": "https://i.cbc.ca/1.5968859.1617052097!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/dhs-wolf.jpg", "publishedAt": "2021-03-29T21:56:55Z", "content": "Suspected Russian hackers gained access to email accounts belonging to the Trump administration's head of the U.S. Department of Homeland Security and members of the department's cybersecurity staff … [+6112 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Samantha Murphy Kelly, CNN Business", "title": "Vaccine passport apps could help us return to normal. First they need to solve the trust problem", "description": "The next time you attend a wedding or concert, visit a place of worship, eat indoors at a restaurant or even go to work, you may need to show digital proof of vaccination or negative Covid-19 test results.", "url": "https://www.cnn.com/2021/03/29/tech/vaccine-passport-app-privacy/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324154623-01-new-york-excelsior-pass-ibm-super-tease.jpg", "publishedAt": "2021-03-29T18:23:05Z", "content": "(CNN)The next time you attend a wedding or concert, visit a place of worship, eat indoors at a restaurant or even go to work, you may need to show digital proof of vaccination or negative Covid-19 te… [+5455 chars]" }, { "source": { "id": "the-globe-and-mail", "name": "The Globe And Mail" }, "author": null, "title": "Reddit to open Toronto office as U.S. tech firms expand in Canada - The Globe and Mail", "description": "The company said its Canadian user base is growing at a rate of more than 40 per cent year over year, and that they don’t necessarily overlap with traditional social-media users", "url": "https://www.theglobeandmail.com/business/article-reddit-to-open-toronto-office-as-us-tech-firms-expand-in-canada/", "urlToImage": "https://www.theglobeandmail.com/resizer/Hp1CCB57XMFHtoHudRhQ1C_75FE=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/DMLBCJJ4C5MCFHXEF7QFPYPHCI.JPG", "publishedAt": "2021-03-29T09:00:00Z", "content": "The company said its Canadian user base is growing at a rate of more than 40 per cent year over year, and that they dont necessarily overlap with traditional social-media users.\r\nDADO RUVIC/Reuters\r\n… [+5234 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Paul R. La Monica, CNN Business", "title": "Here's why Cathie Wood and Kevin O'Leary are still bullish on growth stocks", "description": "Tech stocks have taken a hit lately as investors continue to seek comfort in banks, big oil and other value sectors. But some fans of trendy momentum stocks aren't giving up on them just yet.", "url": "https://www.cnn.com/2021/03/25/investing/cathie-wood-kevin-oleary-vaneck-stocks/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210325113901-cathie-wood-kevin-oleary-jan-van-eck-restricted-super-tease.jpg", "publishedAt": "2021-03-25T18:01:16Z", "content": "New York (CNN Business)Tech stocks have taken a hit lately as investors continue to seek comfort in banks, big oil and other value sectors. But some fans of trendy momentum stocks aren't giving up on… [+4491 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "By Michael Andronico", "title": "Looking for an Xbox Series X? Here's how to have the best shot", "description": "Still looking for an Xbox Series X? Here's how to have the best shot at securing Microsoft's latest game consoles.", "url": "https://www.cnn.com/2021/03/25/cnn-underscored/xbox-series-x-restock/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/201104193945-5-xbox-series-x-review-underscored-super-169.jpg", "publishedAt": "2021-03-25T17:30:12Z", "content": "If youre reading this, chances are you havent gotten your hands on an Xbox Series X or Xbox Series S yet. And youre far from alone just like with the PS5, finding Microsofts newest consoles has been … [+7159 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Anna Bahney, CNN Business", "title": "How four working mothers are doing a year into the pandemic", "description": "It was only supposed to be for a few weeks. A few months at most. One year ago, when the pandemic shut down offices and schools, many working parents were forced to shoehorn their working lives and the school lives of their children into one place: their home…", "url": "https://www.cnn.com/2021/03/24/success/one-year-later-parents-mothers-working-from-home-feseries/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324103200-restricted-01-maira-wenzel-super-tease.jpg", "publishedAt": "2021-03-24T14:51:29Z", "content": "It was only supposed to be for a few weeks. A few months at most. One year ago, when the pandemic shut down offices and schools, many working parents were forced to shoehorn their working lives and t… [+7711 chars]" }, { "source": { "id": "cnn", "name": "CNN" }, "author": "Paul R. La Monica, CNN Business", "title": "Fed up with FAANG and meme stocks? Here's a new investing strategy", "description": "Stop us if you've heard this before. Giant tech stocks are finally due for a prolonged cooling-off period and investors need to start adding more value stocks, such as banks, oil firms and retailers, to their portfolios as the economy recovers.", "url": "https://www.cnn.com/2021/03/24/investing/stocks-value-growth/index.html", "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210323101259-nyse-0922-restricted-super-tease.jpg", "publishedAt": "2021-03-24T11:16:40Z", "content": "New York (CNN Business)Stop us if you've heard this before. Giant tech stocks are finally due for a prolonged cooling-off period and investors need to start adding more value stocks, such as banks, o… [+5541 chars]" }, { "source": { "id": "cbc-news", "name": "CBC News" }, "author": "Reuters", "title": "Microsoft to allow more employees to work in office again starting next week", "description": "Microsoft Corp. will start allowing more employees to work from its headquarters in Redmond, Washington and nearby campuses as soon as next week.", "url": "https://www.cbc.ca/news/business/microsoft-office-1.5960239", "urlToImage": "https://i.cbc.ca/1.5678543.1596831291!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/usa-tiktok-navarro.jpg", "publishedAt": "2021-03-23T13:49:44Z", "content": "Microsoft Corp. will start allowing more employees to work from its headquarters in Redmond, Washington and nearby campuses as soon as next week.\r\nEmployees working at Redmond sites or nearby campuse… [+863 chars]" }, { "source": { "id": "the-globe-and-mail", "name": "The Globe And Mail" }, "author": "Reuters", "title": "Microsoft in talks to acquire messaging platform Discord for more than $10-billion: report - The Globe and Mail", "description": "<ol><li>Microsoft in talks to acquire messaging platform Discord for more than $10-billion: report The Globe and Mail\r\n</li><li>Microsoft in talks to buy Discord Thurrott.com\r\n</li><li>Report: Discord is looking for a buyer, price tag could exceed $10 billi…", "url": "https://www.theglobeandmail.com/business/technology/article-microsoft-in-talks-to-acquire-messaging-platform-discord-for-more-than/", "urlToImage": "https://www.theglobeandmail.com/resizer/jigGCnmeypiACH3xjn0LvCYpfDg=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/ANFYLDICZFJTLLZKBRJVVUQLEQ.JPG", "publishedAt": "2021-03-23T11:11:43Z", "content": "Microsoft Corp. MSFT-Q is in talks to buy messaging platform Discord Inc for more than $10-billion, Bloomberg News reported, citing people familiar with the matter.\r\nDiscord has reached out to potent… [+1464 chars]" }, { "source": { "id": "google-news", "name": "Google News" }, "author": "James Serra", "title": "A new WordPress theme and a new job", "description": "As you can tell, I have switched to a new WordPress theme for this blog site. I have now been blogging for ten years! It seemed like a good...\nThe post A new WordPress theme and a new job appeared first on SQLServerCentral.", "url": "http://feedproxy.google.com/~r/JamesSerra/~3/moPhw0kSwGQ/", "urlToImage": "https://s.w.org/images/core/emoji/13.0.1/72x72/1f642.png", "publishedAt": "2021-03-20T21:14:48Z", "content": "As you can tell, I have switched to a new WordPress theme for this blog site. I have now been blogging for ten years! It seemed like a good time to finally make a change \r\nSpeaking of which, I have a… [+1295 chars]" } ] } class ListNewsAdapter extends BaseAdapter { private final ArrayList<HashMap<String, String>> data; private final Context context; boolean isThemeDark; GetSettings getSettings; int imageViewDimen; ListNewsAdapter(Context c, ArrayList<HashMap<String, String>> d) { context = c; data=d; getSettings = new GetSettings(context); //for checking dark theme imageViewDimen = (int) context.getResources().getDimension(R.dimen.imageViewNews); } public int getCount() { isThemeDark = getSettings.isThemeDark(); //one time check of dark theme return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ListNewsViewHolder holder = new ListNewsViewHolder(); if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.template_list_news, parent, false); holder.galleryImage = convertView.findViewById(R.id.galleryImage); holder.source = convertView.findViewById(R.id.source); holder.title = convertView.findViewById(R.id.title); holder.sdetails = convertView.findViewById(R.id.sdetails); holder.time = convertView.findViewById(R.id.time); convertView.setTag(holder); } else { holder = (ListNewsViewHolder) convertView.getTag(); } holder.galleryImage.setId(position); holder.source.setId(position); holder.title.setId(position); holder.sdetails.setId(position); holder.time.setId(position); HashMap<String, String> holderMap; holderMap = data.get(position); try{ final String KEY_SOURCE = "source"; final String KEY_TITLE = "title"; final String KEY_DESCRIPTION = "description"; final String KEY_URLTOIMAGE = "urlToImage"; final String KEY_PUBLISHEDAT = "publishedAt"; Date date = null; #SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", new Locale("en")); //TODO system language or article language try { date = dateFormat.parse(Objects.requireNonNull(holderMap.get(KEY_PUBLISHEDAT))); } catch (ParseException ignored) { } dateFormat.applyPattern("MMM d, yyyy"); if (date != null) { //simple error check holder.time.setText(dateFormat.format(date)); } //fill in the details for the article holder.source.setText(holderMap.get(KEY_SOURCE)); holder.title.setText(holderMap.get(KEY_TITLE)); holder.sdetails.setText(holderMap.get(KEY_DESCRIPTION)); if (isThemeDark) { //set the text colour depending on dark theme //TODO GET PROPER COLORS holder.title.setTextColor(Color.WHITE); holder.sdetails.setTextColor(Color.WHITE); } else { holder.title.setTextColor(Color.BLACK); holder.sdetails.setTextColor(Color.BLACK); } int colorAccent = getAccentTextColor(); //set the source and time to the accent colour holder.source.setTextColor(colorAccent); holder.time.setTextColor(colorAccent); if(holderMap.get(KEY_URLTOIMAGE) == null || Objects.requireNonNull(holderMap.get(KEY_URLTOIMAGE)).length() < 5) { holder.galleryImage.setImageResource(R.drawable.placeholder_image); } else { Picasso.get() .load(holderMap.get(KEY_URLTOIMAGE).replaceFirst("^http:","https:")) //stop insecure pages .resize(imageViewDimen, imageViewDimen) .centerCrop() .into(holder.galleryImage); } }catch(Exception ignored) {} return convertView; } }
How to read from a local JSON file in android studio and add to an ArrayList?
I am having difficulty reading from a local json file stored in my assets folder. Here is the method I wrote to read from the file and add the objects the birdList ArrayList. Where am I going wrong? public void getJSON() { String jsonString; try { InputStream inputStream = getAssets().open("birds.json"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); jsonString = new String(buffer, "UTF-8"); JSONArray jsonArray = new JSONArray(jsonString); Log.e("MainActivity", "The json is: " + jsonString); for(int i = 0; i < jsonArray.length();i++){ JSONObject obj = jsonArray.getJSONObject(i); Bird bird = new Bird(); bird.setScientificName(obj.getString("scientific_name")); bird.setCommonName(obj.getString("common_name")); bird.setNumberImage(obj.getString("image")); bird.setDescription(obj.getString("description")); birdList.add(bird); } } catch (Exception e) { e.printStackTrace(); } } Here is the json file I am reading from. { "birds": [ { "scientific_name": "Cyanocitta stelleri", "common_name": "Steller's jay", "image": "stellers_jay", "description": "The Steller's jay is a jay native to western North America, closely related to the blue jay found in the rest of the continent, but with a black head and upper body. It is also known as the long-crested jay, mountain jay, Braham's jay and pine jay. It is the only crested jay west of the Rocky Mountains." }, { "scientific_name": "Tachycineta thalassina", "common_name": "Violet-green swallow", "image": "violet_green_swallow", "description": "The violet-green swallow is a small North American passerine bird in the swallow family. These aerial insectivores are distributed along the west coast from Alaska to Mexico, extending as far east as Montana and Texas. With an appearance very similar to the tree swallow, these individuals can be identified by the white rump side-patches that appear to separate their green back and purple tail. " }, { "scientific_name": "Turdus migratorius", "common_name": "American robin", "image": "american_robin", "description": "The American robin is a migratory songbird of the true thrush genus and Turdidae, the wider thrush family. It is named after the European robin[2] because of its reddish-orange breast, though the two species are not closely related, with the European robin belonging to the Old World flycatcher family. The American robin is widely distributed throughout North America, wintering from southern Canada to central Mexico and along the Pacific Coast. " } ] } Any help would be greatly appreciated
Your json starts from {}, so firstly you should write JSONObject jsonobject = new JSONObject(jsonString); Rest is ok
Swagger API Annotation for Java using Enum as options which break request
I have a class defined called Website Locale which lits all supported locales for my site public enum WebsiteLocale { AU ("au", 5, "en", "AUD"), // Australia CA ("ca", 6, "en", "CAD"), // Canada DE ("de", 1, "de", "EUR"), // Germany ES ("es", 1, "es", "EUR"), // Spain ES_US ("es-us", 2, "es", "USD"), // USA, Spanish language EU ("eu", 4, "en", "EUR"), // Europe: English and Euros FR ("fr", 1, "fr", "EUR"), // France FR_US ("fr-us", 2, "fr", "USD"), // USA, French language IT ("it", 1, "it", "EUR"), // Italy NL ("nl", 3, "en", "EUR"), // Netherlands UK ("uk", 1, "en", "GBP"), // UK US ("us", 2, "en", "USD"); // USA ... getters / setters... } In my API resource I have the following annotation #GET #Path("/countries") #ApiOperation("Get countries") #CacheControl(maxAge = 1, maxAgeUnit = TimeUnit.HOURS) #Override public List<CountryDto> getCountries( #QueryParam("websiteLocale") #ApiParam(required = true, defaultValue = "uk") final WebsiteLocale websiteLocale) { return delegate.getCountries(websiteLocale); In the Swagger API test page for that endpoint it gives the accepted values as the Enum literals themselves e.g. AU, CA, DE, ES, ES_US, EU, FR, FR_US This breaks the controller (404 not found response) because it is looking for the associated string key for that enum i.e. au, ca, de, es, es-us, eu, fr, fr-us I had a look through swagger but could not see any specific annotation to look for a part of the enum properties. Any ideas? Thanks
Displaying Data in a Table Android Development?
Working on my first app for android and want to display some data in a table(or something similar). After looking around here I guess android does not support something like a JTable; someone said you have to create a custom table? What is the best way to display data that is a string in CSV format? In a Java app I created I have a function that creates a 2D Array out of the string and throws that into a JTable. Data Format in String: Sun 02-16-14 09:45 PM,1,REAL TIRED,JUST WACK AT IT,2 - 4, Sun 02-23-14 08:10 PM,1,BALLERS,REAL TIRED,4 - 11, Sun 03-02-14 09:00 PM,1,REAL TIRED,EL TRI,1 - 7, Sun 03-09-14 05:50 PM,1,GO GO POWER RANGERS,REAL TIRED,4 - 9, Sun 03-16-14 06:40 PM,1,REAL TIRED,GAME OF GROANS,16 - 0, Sun 03-23-14 09:00 PM,1,HUNGOVER HAT TRICKS,REAL TIRED, Sun 03-30-14 07:25 PM,1,REAL TIRED,PRESTIGE WORLD WIDE, Sun 04-06-14 04:20 PM,1,REAL TIRED,BALLERS, Not sure if there are any good options because of the limited space for mobile devices. Maybe only display one row at a time and be able to click through them?
You can try this example, you will be very comfortable with this code. Even though if you want to add rows in the table view dynamically from an server or from an API call then just create a for loop and add it according this example. public class MainActivity extends Activity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama", "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama", "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama" }; ScrollView scrollView = new ScrollView(this); TableLayout tableLayout = new TableLayout(this); for (int i = 0; i < presidents.length; i++) { TableRow tableRow = new TableRow(this); TextView tv = new TextView(this); tv.setPadding(10, 10, 10, 10); tv.setGravity(Gravity.CENTER); tv.setText(presidents[i]); tableRow.addView(tv); tableLayout.addView(tableRow); View v = new View(this); v.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 1)); v.setBackgroundColor(Color.rgb(51, 51, 51)); tableLayout.addView(v); } scrollView.addView(tableLayout); setContentView(scrollView); } } Hope so you would like this. If this is suitable to you then please mark as accepted answer so that it could be helpful for others.
JSON Parsing using minimal-json and Gson
I have a java program which retrieves data for a particular TV show and returns a JSON response with the details. My problem is with parsing the JSON response to get one particular key-value pair, namely the "first_aired_iso" string, which gives the air date for that episode. Here is the URL which calls the API String api_url = "http://api.trakt.tv/show/season.json/<api-key>/the-walking-dead/1"; And here is the corresponding JSON response ! [ { "season":1, "episode":1, "number":1, "tvdb_id":2493011, "title":"Days Gone Bye", "overview":"Rick searches for his family after emerging from a coma into a world terrorized by the walking dead. Morgan and Duane, whom he meets along the way, help teach Rick the new rules for survival.", "first_aired":1288584000, "first_aired_iso":"2010-10-31T21:00:00-05:00", "first_aired_utc":1288598400, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/1", "screen":"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg" }, "ratings":{ "percentage":89, "votes":763, "loved":733, "hated":30 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":false, "rating_advanced":0 }, { "season":1, "episode":2, "number":2, "tvdb_id":2493181, "title":"Guts", "overview":"Rick unknowingly causes a group of survivors to be trapped by walkers. The group dynamic devolves from accusations to violence, as Rick must confront an enemy far more dangerous than the undead.", "first_aired":1289192400, "first_aired_iso":"2010-11-07T21:00:00-06:00", "first_aired_utc":1289210400, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/2", "screen":"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg" }, "ratings":{ "percentage":87, "votes":533, "loved":507, "hated":26 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":false, "rating_advanced":0 }, { "season":1, "episode":3, "number":3, "tvdb_id":2656081, "title":"Tell It to the Frogs", "overview":"After returning to the camp with the department store survivors and an emotional reunion with his wife and son, Rick decides to go against Shane's advice and go back to Atlanta for Merle Dixon and his dropped bag of guns accompanied by Merle's younger brother, Darryl Dixon, as well as Glenn and T-Dog.", "first_aired":1289797200, "first_aired_iso":"2010-11-14T21:00:00-06:00", "first_aired_utc":1289815200, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/3", "screen":"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg" }, "ratings":{ "percentage":85, "votes":484, "loved":458, "hated":26 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":false, "rating_advanced":0 }, { "season":1, "episode":4, "number":4, "tvdb_id":2656091, "title":"Vatos", "overview":"While still in search of Merle, the group tries to retrieve the bag of guns but are attacked by several living men who are also after the weapons. The group manages to grab the injured attacker; however, several of the attackers escape and take Glenn hostage. Back at camp a large group of walkers venture up the hill and take the survivors by surprise.", "first_aired":1290402000, "first_aired_iso":"2010-11-21T21:00:00-06:00", "first_aired_utc":1290420000, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/4", "screen":"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg" }, "ratings":{ "percentage":88, "votes":490, "loved":467, "hated":23 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":false, "rating_advanced":0 }, { "season":1, "episode":5, "number":5, "tvdb_id":2656101, "title":"Wildfire", "overview":"Rick leads the group to the CDC after the attack on the camp. Jim must make a terrible life and death decision.", "first_aired":1291006800, "first_aired_iso":"2010-11-28T21:00:00-06:00", "first_aired_utc":1291024800, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/5", "screen":"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg" }, "ratings":{ "percentage":87, "votes":460, "loved":443, "hated":17 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":"love", "rating_advanced":10 }, { "season":1, "episode":6, "number":6, "tvdb_id":2656111, "title":"TS-19", "overview":"Rick and the group are allowed into the CDC by a strange doctor, but all is not what it seems in their newfound haven. ", "first_aired":1291611600, "first_aired_iso":"2010-12-05T21:00:00-06:00", "first_aired_utc":1291629600, "url":"http://trakt.tv/show/the-walking-dead/season/1/episode/6", "screen":"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg", "images":{ "screen":"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg" }, "ratings":{ "percentage":87, "votes":465, "loved":440, "hated":25 }, "watched":true, "in_collection":true, "in_watchlist":false, "rating":"love", "rating_advanced":10 } ] Well, you get the idea... I just need to extract the key value for "first_aired_iso" for each episode. Here is my code to do that String s = response.toString(); Gson gson = new Gson(); String jsonstr = gson.toJson(s); System.out.println(jsonstr); JsonArray json = JsonArray.readFrom(jsonstr); for (int i = 0; i < 15; i++) { System.out.println(json.get(i).asString()); } Problem is, there is absolutely no response after printing the raw JSON output. I can't get it to enter the loop at all. For reference, please check http://eclipsesource.com/blogs/2013/04/18/minimal-json-parser-for-java/
My solution: public static void main(String[] args) { String json = "[ { \"season\":1, \"episode\":1, \"number\":1, \"tvdb_id\":2493011, \"title\":\"Days Gone Bye\", \"overview\":\"Rick searches for his family after emerging from a coma into a world terrorized by the walking dead. Morgan and Duane, whom he meets along the way, help teach Rick the new rules for survival.\", \"first_aired\":1288584000, \"first_aired_iso\":\"2010-10-31T21:00:00-05:00\", \"first_aired_utc\":1288598400, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/1\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg\" }, \"ratings\":{ \"percentage\":89, \"votes\":763, \"loved\":733, \"hated\":30 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":2, \"number\":2, \"tvdb_id\":2493181, \"title\":\"Guts\", \"overview\":\"Rick unknowingly causes a group of survivors to be trapped by walkers. The group dynamic devolves from accusations to violence, as Rick must confront an enemy far more dangerous than the undead.\", \"first_aired\":1289192400, \"first_aired_iso\":\"2010-11-07T21:00:00-06:00\", \"first_aired_utc\":1289210400, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/2\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":533, \"loved\":507, \"hated\":26 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":3, \"number\":3, \"tvdb_id\":2656081, \"title\":\"Tell It to the Frogs\", \"overview\":\"After returning to the camp with the department store survivors and an emotional reunion with his wife and son, Rick decides to go against Shane's advice and go back to Atlanta for Merle Dixon and his dropped bag of guns accompanied by Merle's younger brother, Darryl Dixon, as well as Glenn and T-Dog.\", \"first_aired\":1289797200, \"first_aired_iso\":\"2010-11-14T21:00:00-06:00\", \"first_aired_utc\":1289815200, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/3\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg\" }, \"ratings\":{ \"percentage\":85, \"votes\":484, \"loved\":458, \"hated\":26 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":4, \"number\":4, \"tvdb_id\":2656091, \"title\":\"Vatos\", \"overview\":\"While still in search of Merle, the group tries to retrieve the bag of guns but are attacked by several living men who are also after the weapons. The group manages to grab the injured attacker; however, several of the attackers escape and take Glenn hostage. Back at camp a large group of walkers venture up the hill and take the survivors by surprise.\", \"first_aired\":1290402000, \"first_aired_iso\":\"2010-11-21T21:00:00-06:00\", \"first_aired_utc\":1290420000, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/4\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg\" }, \"ratings\":{ \"percentage\":88, \"votes\":490, \"loved\":467, \"hated\":23 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":5, \"number\":5, \"tvdb_id\":2656101, \"title\":\"Wildfire\", \"overview\":\"Rick leads the group to the CDC after the attack on the camp. Jim must make a terrible life and death decision.\", \"first_aired\":1291006800, \"first_aired_iso\":\"2010-11-28T21:00:00-06:00\", \"first_aired_utc\":1291024800, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/5\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":460, \"loved\":443, \"hated\":17 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":\"love\", \"rating_advanced\":10 }, { \"season\":1, \"episode\":6, \"number\":6, \"tvdb_id\":2656111, \"title\":\"TS-19\", \"overview\":\"Rick and the group are allowed into the CDC by a strange doctor, but all is not what it seems in their newfound haven. \", \"first_aired\":1291611600, \"first_aired_iso\":\"2010-12-05T21:00:00-06:00\", \"first_aired_utc\":1291629600, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/6\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":465, \"loved\":440, \"hated\":25 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":\"love\", \"rating_advanced\":10 } ]"; ArrayList<Map> al = new Gson().fromJson(json, ArrayList.class); for(Map m : al){ System.out.printf("Ep. %.0f aired on %s\n", m.get("episode"), m.get("first_aired_iso")); } } This is the execution: 1 aired on 2010-10-31T21:00:00-05:00 2 aired on 2010-11-07T21:00:00-06:00 3 aired on 2010-11-14T21:00:00-06:00 4 aired on 2010-11-21T21:00:00-06:00 5 aired on 2010-11-28T21:00:00-06:00 6 aired on 2010-12-05T21:00:00-06:00 You should always let Gson do the work for you. In this case you have an list of objects (map). So tell Gson to deserialize in that way and access to the structure using generic for loop and map access.
String s = response.toString(); JsonArray json = JsonArray.readFrom(s); for (int i = 0; i < json.size(); i++) { JsonObject show = json.get(i).asObject(); int episode = show.get("episode").asInt(); String time = show.get("first_aired_iso").asString(); System.out.println("Episode " + episode + " - " + time); } Thanks a lot HotLicks! :)