Last active
January 20, 2016 13:01
-
-
Save arjones/1b3a1473b6c5a9fa20bd to your computer and use it in GitHub Desktop.
Scala Json Parser Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONObject | |
case class Item(id: String, category: String, soldQuantity: Integer, price: Double, currencyId: String, | |
sellerId: Long, officialStoreId: String, condition: String, acceptMP: Boolean) | |
object JsonParser { | |
def parseSearch(json: String): List[Item] = { | |
try { | |
// catch exception when the JSONStr is malformed | |
val o = new JSONObject(json) | |
val elems = o.getJSONArray("results") | |
val items = for (idx <- 0 to elems.length() - 1) yield { | |
try { | |
// catch exception when one of the results doesn't contains all the required fields | |
val elem = elems.getJSONObject(idx) | |
val id = elem.getString("id") | |
val siteId = elem.getString("site_id") | |
val title = elem.getString("title") | |
val sellerId = elem.getJSONObject("seller").getLong("id") | |
val price = elem.getDouble("price") | |
val currencyId = elem.getString("currency_id") | |
val availableQuantity = elem.getInt("available_quantity") | |
val soldQuantity = elem.getInt("sold_quantity") | |
val buyingMode = elem.getString("buying_mode") | |
val listingType = elem.getString("listing_type_id") | |
val stopTime = elem.getString("stop_time") | |
val condition = elem.getString("condition") | |
val permalink = elem.getString("permalink") | |
val thumbnail = elem.getString("thumbnail") | |
val acceptsMercadoPago = elem.getBoolean("accepts_mercadopago") | |
val officialStoreId = elem.getString("official_store_id") | |
val categoryId = elem.getString("category_id") | |
Some(Item(id, categoryId, soldQuantity, price, currencyId, sellerId, officialStoreId, condition, acceptsMercadoPago)) | |
} catch { | |
case e: Exception => { | |
e.printStackTrace() | |
None | |
} | |
} | |
} | |
items.flatMap(e => e).toList | |
} catch { | |
case e: Exception => { | |
e.printStackTrace() | |
List[Item]() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment