mgholam / fastJSON

Smallest, fastest polymorphic JSON serializer
https://www.codeproject.com/Articles/159450/fastJSON-Smallest-Fastest-Polymorphic-JSON-Seriali
MIT License
479 stars 147 forks source link

ToObject from parsed result #94

Closed xmedeko closed 3 years ago

xmedeko commented 5 years ago

I would like to have JSON.ToObject() method working with the parsed content already.

I need to do fastJSON.JSON.Parse(string) examine the result dictionary and then make objects from some dictionary values. E.g. the input may be following strings:

I do (IDictionary<string, object>)JSON.Parse(msg), examine if it contains data1 or data2, and then I need to create the Data1 or the Data2 object from the appropriate part of json. (This is a very simplified scenario of my real problem.) Current solution is:

  1. Convert the part of json to string and then call JSON.ToObject.
  2. Parse the object manually from (IDictionary<string, object>)

I would like call directly some method like JSON.ToObject(IDictionary<string, object> json) instead.

mgholam commented 5 years ago

I guess you can add this overload assuming you tell ToObject<T> what the T is since it would not be in the dictionary structure (it would be at the start of the json string).

xmedeko commented 5 years ago

I mean something like this:

// JSON
public static object ToObject(object o, Type type)
{
    return new deserializer(Parameters).ToObject(o, type);
}

// deserializer - split ToObject
public object ToObject(string json, Type type)
{
    object o = new JsonParser(json, _params.AllowNonQuotedKeys).Decode();
    if (o == null)
        return null;
    return ToObject(o, type);
}

public object ToObject(object o, Type type)
{
    // ... rest of the ToObject code
}

Maybe the method should have other name. Also, it's necessary to add methods with generics, and something like FillObject. I can try to make a PR if you like.