Validation error while trying to parse a json array to List[Object] in Scala - arrays

I have a method that returns a JsArray of a type Foo.
To process the response, I am doing the following:
val foos : List[Foo] = Json.toJson(result).as[List[Foo]]
While debugging, I could see that the result is comming as:
"[]"
and it is generated by the code:
Ok(Json.toJson(foos))
Where foos is a List[Foo]
But I am getting the error:
[JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsarray,WrappedArray())))))]
I've tried many ways, but can't solve this.
What I am doing wrong?

You're most likely looking for Json.parse, rather than Json.toJson.
import play.api.libs.json.Json
scala> Json.toJson("[]")
res0: play.api.libs.json.JsValue = "[]"
scala> Json.parse("[]")
res1: play.api.libs.json.JsValue = []
Trying to convert res0 to a List[Foo] doesn't work because you're trying to convert the string "[]" rather than than the same string without quotation marks, [].

It seems like you have it the wrong way around. Json.toJson(value) is used to convert from a Scala object to a JSON value. You are using it incorrectly to try and read a JSON body and convert it to a Scala object. You probably want to do something like this:
val foos : JsResult[List[Foo]] = result.validate[List[Foo]]
where result is your JSON value.
Look at this, under the 'JsValue to a model' section:
https://www.playframework.com/documentation/2.6.x/ScalaJson

Related

Parameterize() must be of the type array, string given in Laravel 5.2

i am using laravel 5.2 and trying to update records using whereIn('id',[1,2]) but when i try to pass a json value [1,2] to it , i returns
parameterize() must be of the type array, string given. I am mentioning my code below.
$load_id=json_encode($request->chk_load,JSON_NUMERIC_CHECK); // it returns [1,2]
Load::whereIn('id',$load_id)->update(array('status'=>3));
What should i do to fix this error. ?
seems json_encode($request->chk_load,JSON_NUMERIC_CHECK);
returns json string and not an array..
can you elaboarate $request->chk_load is what kind of data it is?

Storing values obtained from for each loop Scala

Scala beginner who is trying to store values obtains in a Scala foreach loop but failing miserably.
The basic foreach loop looks like this currently:
order.orderList.foreach((x: OrderRef) => {
val references = x.ref}))
When run this foreach loop will execute twice and return a reference each time. I'm trying to capture the reference value it returns on each run (so two references in either a list or array form so I can access these values later)
I'm really confused about how to go about doing this...
I attempted to retrieve and store the values as an array but when ran, the array list doesn't seem to hold any values.
This was my attempt:
val newArray = Array(order.orderList.foreach((x: OrderRef) => {
val references = x.ref
}))
println(newArray)
Any advice would be much appreciated. If there is a better way to achieve this, please share. Thanks
Use map instead of foreach
order.orderList.map((x: OrderRef) => {x.ref}))
Also val references = x.ref doesn't return anything. It create new local variable and assign value to it.
Agree with answer 1, and I believe the reason is below:
Return of 'foreach' or 'for' should be 'Unit', and 'map' is an with an changed type result like example below:
def map[B](f: (A) ⇒ B): Array[B]
Compare To for and foreach, the prototype should be like this
def foreach(f: (A) ⇒ Unit): Unit
So If you wanna to get an changed data which is maped from your source data, considering more about functions like map, flatMap, and these functions will traverse all datas like for and foreach(except with yield), but with return values.

"no implicit conversion of Array into String" when trying to parse JSON data

I’m using Rails 4.2.3. I’m trying to parse JSON data, so I have
content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"]
my_object_times_array = JSON.parse(content)
Sadly, the second line gives the error
no implicit conversion of Array into String
The JSON is well-formed (at least as far as I can tell) so I’m not sure what is causing the error above and how to fix it. I would prefer not to change the JSON.
content is an array, but JSON.parse expects a JSON String.
Example of usage from the documentation:
require 'json'
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
Check the documentation here
So you could do following:
content = "{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"
my_object_times_array = JSON.parse(content)
or
content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData\":[{\"externalId\":\"4279\"}]}"]
my_object_times_array = JSON.parse(content[0])

Encoding toJSON from Arrays and Dictionaries in Swift

I am trying to create a JSON file from an array that i make inside my application with swift.
I need to encode to JSON an 'Array' because i am creating dictionaries and arrays before and i just combine them to that array.
In my code i have :
var order = Array<Any>()
var orderArray = Array<Dictionary<String, String>>()
var dict = Dictionary<String, Any>()
and i put first the orderArray in dict and then the dict inside order.
The output if i print it is correct and it works. The problem is when i try to encode the order(array) into JSON. Then i get the following error:
Cannot invoke 'dataWithJSONObject' with an argument list of type '(Array'
This is the code i use:
let json = NSJSONSerialization.dataWithJSONObject(order, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
If i try the same code with the orderArray for example it works.
The 'Any' i think does the mess. But how could i resolve this?
Thank you.

Parse.com Query with swift 1.2 and string array

I am trying to query from parse.com and I would db receiving about 100 objects per time. I used the swift example code on their website, and the app doesn't build with that code. So I looked around and found that people were using code similar to this:
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
// do something
self.myDataArray = objects as! [String]
})
This does not work, because I am trying to convert PFObject to String
I would need to get the one one value from each object into a swift string array [String]. How do I get just the one text value, instead of the PFObject and how do I get it into the swift string array?
I don't speak swift very well, but the problem with the code is it's trying to cast the returned PFObject to a string, but you want to extract a string attribute, so (if you really want to do it):
for object in objects {
var someString = object.valueForKey("someAttributeName") as String
self.myDataArray.addObject(someString)
}
But please make sure you need to do this. I've noticed a lot of new parse/swift users (especially those who are populating tables) have the urge to discard the returned PFObjects in favor of just one of their attributes. Consider keeping the PFObjects and extracting the attributes later as you need them. You might find you'll need other attributes, too.
For starters, I would definitely recommend using the "if let" pattern to qualify your incoming data. This is a nice Swift feature that will help avoid run-time errors.
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock(
{ (objects: [AnyObject]?, error: NSError?) -> Void in
// check your incoming data and try to cast to array of "posts" objects.
if let foundPosts = objects as? [posts]
{
// iterate over posts and try to extract the attribute you're after
for post in foundPosts
{
// this won't crash if the value is nil
if let foundString = post.objectForKey("keyForStringYouWant") as? String
{
// found a good data value and was able to cast to string, add it to your array!
self.myDataArray.addObject(foundString)
}
}
})

Resources