skip to Main Content

I have some json string come from c++, std::multimap<double,std::string>,this json string such as:

"{"name":"mark","data":[1,2,3,4],"some":"11.1":"Hello","22.2":",","44.4":"World"}}".

When I try to use mormot to deserialize this JSON string, it is failure, I don’t have a appropriate struct to receive it!

So, in Delphi, How can I deserialize this json string :"{"1.1":"Hello","2.2":"world"}" to TDictionary<double,string>?

2

Answers


  1. Chosen as BEST ANSWER

    this is my test code,it can work now.thanks!

    TDstring = TDictionary<double, string>;

    class procedure c_method.CustomReadClass(var Context: TJsonParserContext; Instance: TObject);
    var doc: TDocVariantData;
    begin
      if Context.ParseObject then
      begin
        if not assigned(Instance) then Instance := TDstring.Create;
    
        TDstring(Instance).Clear;
    
        var s : u8string := add_bracket(Context.json); //'{ ' + Context.json + ' }'
    
        doc.InitJson(s);
        var nameList := doc.Names;
    
        for var i :integer := 0 to High(nameList) do
        begin
          TDstring(Instance).TryAdd(To_string(nameList[i]).ToDouble, doc.s[nameList[i]]);
        end;
    
        Context.ParseEndOfObject;
        Context.Valid := true;
      end;
    
    end;
    
    initialization
    TRttiJson.RegisterCustomSerializerClass(TDstring, c_method.CustomReadClass, nil);
    
    finalization
    TRttiJson.UnRegisterCustomSerializerClass(TDstring);
    

  2. I am sure there are many ways of doing this. We use the SuperObject library.

    Include SuperObject in your uses clause and then you can parse your object and access the values like this…

    var
      obj: ISuperObject;
      val: string;
    begin
      obj := SO('{"foo": true}');
      { .S is just one of many helper functions. }
      val := obj.AsObject.S['foo']
    end;
    

    If you don’t know the key:value pairs in advance you can iterate over the object like this.

    var
      item: TSuperAvlEntry;
    begin
      for item in obj.AsObject do
      begin
        item.Name;
        item.Value;
      end;
    end;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search