SprayJson: Object is missing required member 'User$u0020ID - spray

Here is my Json
{"preview":false,"offset":0,"result":{"User ID":"ab192013","IP
Address":"101.2.0.11"}}
I have two case classes
case class Sample(result: Result)
case class Result(`User ID` : String , `IP Address`: String)
object MyResultJsonProtocol extends DefaultJsonProtocol {
implicit val ResultFormat = jsonFormat2(Result.apply)
implicit def sampleFormat[jsonformat] = jsonFormat1(Sample.apply)
}
I cannot get user ID value
Please help, I get the exception below
MalformedContent(Object is missing required member 'User$u0020ID',Some(spray.json.DeserializationException: Object is missing required member 'User$u0020ID'))

Related

Cannot assign type to same type in dart

I have this code below. I want to create BST but when I try to implement compareTO method inside get function I get the "The argument type 'Key' can't be assigned to the parameter type 'Key'.dartargument_type_not_assignable" error which does not make sense to me because it basically says cannot assign to the same type. Can anybody explain this? I commented on the erogenous line below.
class Key extends Comparable<Key> {
num key;
Key(this.key);
#override
int compareTo(Key other) {
return key.compareTo(other.key);
}
}
class Value {
dynamic value;
}
class Node {
Key key;
Value value;
Node? left, right;
Node(this.key, this.value);
}
class BST<Key extends Comparable<Key>, Value> {
Node? root;
Value get(Key key) {
Node? currentNode = root;
while (currentNode != null) {
int compare = key.compareTo(currentNode.key); // The argument type 'Key' can't be assigned to the parameter type 'Key'.dartargument_type_not_assignable
if (compare > 0) {
currentNode = currentNode.right;
} else if (compare < 0) {
currentNode = currentNode.left;
} else {}
...
...
}
}
I would suggest you to rename BST<Key extends Comparable<Key>, Value> into BST<T extends Comparable<T>, Value> to avoid confusion between the different identifiers Keys.
In BST, Key (let's call it T) refers to a generic type (=T) that extends Comparable<T>.
So T extends Comparable<T>
InBST.get(Key key), Key still refers to the generic type T.
So key has the type T.
Now I supposed that currentNode.key is of type Key (!= T).
key.comparyTo(x) requires x to be a T while currentNode.key is not (it is Key).
It is hard to be clear when you have 2 identifiers with the same name (Key).
As I said at the beginning of my answer, rename
class BST<Key extends Comparable<Key>, Value> {}
into
class BST<T extends Comparable<T>, Value> {}
to have a more understandable error message.
When you do it, the error message should become:
The argument type 'Key' can't be assigned to the parameter type 'T'.

Initialization error when creating an object

When I compile the following code:
class Student {
int id;
Student() {
this.id = 12345;
}
}
void main() {
var student1 = new Student();
}
I get the following error:
Error: Field 'id' should be initialized because its type 'int' doesn't
allow null.
But why do I get this error? I did initialize id in the constructor!
In Dart, the creation of objects are split into two phases:
Initialization of all values.
Execution of constructor body.
So when you are running code inside the constructor body (between the {...} in the constructor definition) then all class defined variables must have been provided a default value that is valid for the type of variable.
In your case, the variable is typed int but are not provided a default value. In Dart, all variable will by default be set to null in case of no other value provided. But since int is a non-nullable type it does not allow null to be a value and the compiler are therefore giving you the error.
The solution are to provide a value before the constructor is running. You can do that like this:
class Student {
int id;
Student() : id = 12345;
}
Or:
class Student {
int id = 12345;
Student(); // The constructor can in theory just be removed here
}
In case you cannot define a value as part of the initialization phase, you can (but should be prevented if possible) mark the variable as late which makes it so you promise, the Dart compiler, that you are going to provide a value for the variable before the first time you are trying to read from that variable:
class Student {
late int id;
Student() {
this.id = 12345;
}
}
In case you are trying to read from id before it have been provided a value, the program will crash with a LateInitializationError at runtime.
And at last, you can set the type to be a nullable type, like int?, to allow the variable to have a default value of null. But doing so will require you to check for null when you are trying to do something with the value in a context where null is not allowed:
class Student {
int? id;
Student() {
this.id = 12345;
}
}

Constructors can't have type parameters.dart(type_parameter_on_constructor)

I am using the following dart packages (json_annotation, json_serializable, build_runner) to serialize/de-serialize json according to this page.
This is my code:
import 'package:json_annotation/json_annotation.dart';
part 'car_type.g.dart';
#JsonSerializable()
class CarType {
final int id;
#JsonKey(name: 'type_label')
final String label;
final String description;
CarType(this.id, this.label, this.description);
factory CarType.fromJson(Map<String, dynamic> json) =>
_$CarTypeFromJson(json);
factory List<CarType> CarType.fromJsonList(dynamic jsonArray){
final list = jsonArray as List;
final carTypesList = list.map((i) => CarType.fromJson(i));
return carTypesList;
}
}
So with the factory List<CarType> CarType.fromJsonList(dynamic jsonArray) I want to pass a json array to get back a list of CarType objects. However I'am getting a couple of compiler errors namely:
This function has a return type of 'List', but doesn't end with a return statement.dart(missing_return)
The default constructor is already defined.dart(duplicate_constructor_default)
Constructors can't have type parameters.dart(type_parameter_on_constructor)
Any idea what is going on?
factory List<CarType> CarType.fromJsonList(dynamic jsonArray){
You can't specify a return type for a constructor.
The return type is always the same as the class the constructor is member of.
Just replace factory with static and you should be fine,
except json_serializable expects a factory constructor, then you need to remove the return type and find another approach to get the List.

Grails bind data to non-domain-class with type checking

I'm looking for a simple way to check some types in my params. If they exist they should have a certain type, if not they should have a default value. If they exist and their type is wrong, an exception should be thrown.
It would be nice to have the values in a handy container afterwards. Therefore I've tried passing params to the container's constructor and bindData on a container object. Neither is successful:
class ContainerClass {
Integer foo = 42;
}
class TestController {
def index(){
//doesn't throw, **even when params.foo = "2asdf3"**
ContainerClass meh = new ContainerClass();
bindData(meh, params);
println meh.foo //prints 42 when params.foo = "2asdf3"
// throws GroovyCastException: Cannot cast object '23' with class
// 'java.lang.String' to to class 'java.lang.Integer',
// **even when params.foo = "23"**
ContainerClass meh2 = new ContainerClass(params);
render "meh"
}
}
I'm using grails 3 if this is of importance.
You might use Command Objects to bind parameters to certain Data Type.
Reference : http://docs.grails.org/latest/guide/single.html?utm_content=bufferf77f5&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer#commandObjects
If you want to throw exceptions if certain data type does not match,that needs to be checked explicitly.

multiple constructors and class inheritance in F#

I am having difficulty to convert following C# code to F#:
class Foo
{
public Foo() { }
public Foo(string name) { }
}
class Bar : Foo
{
public Bar() : base() { }
public Bar(string name) : base(name) { }
public string Name { get; set; }
}
I first tried following, but it is reporting error
Constructors for the type 'Bar' must directly or indirectly call its
implicit object constructor. Use a call to the implicit object
constructor instead of a record expression.
type Foo() =
new(name:string) = Foo()
type Bar() =
inherit Foo()
new(name:string) = { inherit Foo(name) }
member val Name:string = null with get, set
Then I tried following, but it is now reporting error on the auto property
'member val' definitions are only permitted in types with a primary
constructor. Consider adding arguments to your type definition"
type Foo() =
new(name:string) = Foo()
type Bar =
inherit Foo
new(name:string) = { inherit Foo(name) }
member val Name:string = null with get, set
If you want F# source code who compiles to precisely the same API as given by your C# code, the answer is as follows:
type Foo =
new() = {}
new(name:string) = { }
type Bar =
inherit Foo
[<DefaultValue>]
val mutable private name:string
new() = { inherit Foo() }
new(name) = { inherit Foo(name) }
member x.Name with get() = x.name and set v = x.name <- v
This compiles:
type Foo() =
new(name:string) = Foo()
type Bar(name : string) =
inherit Foo()
new() = Bar(null) // or whatever you want as a default.
member val Name:string = name with get, set
See Constructors (F#) and Inheritance (F#).
Looking at the decompilation, the C# would be (with attributes removed):
public class Bar : Program.Foo {
internal string Name#;
public string Name {
get {
return this.Name#;
}
set {
this.Name# = value;
}
}
public Bar(string name) {
this.Name# = name;
}
public Bar() : this(null) {
}
}
public class Foo {
public Foo() {
}
public Foo(string name) : this() {
}
}
If a class has a parameter list directly after its name (including ()), it has a primary constructor. Using it, any inherit declarations are placed only in this primary constructor, which comes directly after the class declaration and before any member declarations.
It is unclear what you are trying to achieve. The class Foo has a constructor taking a string argument, only to discard it. A (technically) valid, similar pair of classes would be this:
type Foo(name:string) =
member f.NameLength = name.Length
type Bar(initialName) = // WARNING: this will not end well
inherit Foo(initialName)
member val Name:string = initialName with get, set
But this is not sensible code. Foo will keep the initial name even if the name in Bar is changed. Bar.Name.Length returns the current name's length, while Bar.NameLength returns the initial name's length.
To keep the default constructor, one could add new () = Bar(null) (or the equivalent in Foo), but please note that null is considered an interop-only feature. It is not used in F# facing code; if possible, use the appropriate option type or an empty string respectively (depending on whether the string is just empty or doesn't exist at all).
Also, inheriting classes is discouraged in the F# component design guidelines -- for good reason. There are few use cases, but those usually involve a tiny base class and a derived class that is a perfect superset of it. It is far more common to compose types by using one class as a member of another.
I don't know how relevant this is, but here is an example of a class with default constructor and an additional constructor that uses it:
type Text500(text : string) =
do if text.Length > 500 then
invalidArg "text" "Text of this type cannot have a length above 500."
member t.Text = text
new () = Text500("")
This utilizes the primary constructor to verify input and has an additional, parameterless constructor that uses an empty string. (I'm not sure if the additional constructor would be useful in actual applications.)

Resources