I'm reading a json from file and serializing to any object as follows:

MyObject o = myjson.FromJson<MyObject>();

The json text is correct as I was using Newtonsoft.Json before moving to ServiceStack.

However, after serializing, the object 'o' is not being set accordingly (ie. empty or with default values set in the object's constructor).

The is the class:

public class Options
{
    public string Email;
    public string Password;
    public string Answer;
    //etc...

    public Options()
    {
        this.Email = "default";
        this.Password = "default";
        //etc...
    }
}

What can be wrong?

有帮助吗?

解决方案

ServiceStack doesn't serialize public fields by default, but you can enable it with:

JsConfig.IncludePublicFields = true;

其他提示

Lets assume your JSON is on a text file.

using Newtonsoft.Json;

    var item = @"C:\someJSON.txt";
    var op = JsonConvert.DeserializeObject<SavedOpData>(File.ReadAllText(item));

My Class for SavedOpData

   internal partial class SavedOpData
        {
            internal class AppUri
            {
                public string file_name;
                public string file_uri;
                public int file_size;
                public string file_hash;
            }
        }

To Serialize it back to JSON do the following:

var serialized = JsonConvert.SerializeObject(SavedOpData);

Assuming SavedOpData is an instance of the class i posted above and it has data already populated.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top