Unable to get the value after parsing with json

I am using a service to get a value from Id but receive. This value needs
to be stringify, parsed and retrieved to another iteration.

Is that code have an issue?

class Test {

 static function getById(id:Int, list:Array<_Category>):_Category {
    var obj:_Category = null;
    for (c in list) {
        if(c.id == id) { //error here
            obj = c;
            break;
        }
    }
    return obj;
}

static function main() {
    var collection = '[{"description":"tellus eu augue porttitor interdum. Sed auctor odio a purus.","id":1,"categoryId":5,"scname":"Jacob Pollard"},{"description":"risus. Donec egestas. Aliquam nec enim. Nunc ut erat. Sed","id":2,"categoryId":4,"scname":"Jana Grant"},{"description":"eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit elit","id":3,"categoryId":3,"scname":"Catherine Floyd"},{"description":"neque sed sem egestas blandit. Nam nulla magna, malesuada vel,","id":4,"categoryId":2,"scname":"Ulla Burks"},{"description":"a neque. Nullam ut nisi a odio semper cursus. Integer","id":5,"categoryId":1,"scname":"Isadora Dalton"}]';
    var list:Array<_Category> = haxe.Json.parse(collection);
    try {

        for(ca in list) {
            var cstr = haxe.Json.stringify(ca);
            var _cat = haxe.Json.parse(cstr);
            trace(_cat.id != 0); //ok
        }

        var c = getById(1, list); // error

    } catch (e:Dynamic) {
        trace("Uncaught exception Unexpected value {description: tellus eu augue porttitor interdum. Sed auctor odio a purus., id: 1, categoryId: 5, scname: Jacob Pollard}, expected instance");
    }
}

}

class _Category {

public var id:Int;
public var cname:String;
public var description:String;
public var cdate:String;
public var edate:String;



public function new() {
    this.cdate = Date.now().toString();
    this.edate = Date.now().toString();
}

}

Use typedef of an anonymous object instead of class for _Category, as Json only supports the basic types and objects.

Something like this:

typedef _Category = {
  var id:Int;
  var ?cname:String;
  var ?description:String;
  var ?cdate:String;
  var ?edate:String;
}

This way the object based on this typedef can be stringified and can be parsed from a string as well (as long as its properties are also known Json types and objects)

Note that you’ll lose the new() constructor, you can just use var cat:_Category = {id:1234} to initialize the object.

Properties marked with ? are optional, the rest are mandatory at initialization.

1 Like

Hi @kopmba

Did you try by defining the _Category class with proper field types? Also, ensure that the JSON parsing is done in a way that returns _Category objects.