문제

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