0

我是 ASP.NET 世界的新手,我正在努力实现以下目标。

我需要序列化这种格式的 API

{
    "results": {
        "profile": {
            "firstname": "John,
            "lastname": "Newman",
        },
        "credit": {
             "amount": 30
        }
    }
}

问题是我不知道如何为我的数据建模。我需要一个结果对象,其中包含 2 个其他对象(个人资料和信用)。您可以在下面看到一些示例代码。

public class Results
{

    public class Data {
        public Profile profile { get; set; }
        public Credit credit {get; set; }
    }

    public class Profile {
        public String firstname {get; set; }
        public String lastname { get; set; }
    }

    public class Credit {
        public int amount { get; set; }
    }
}

static void Main(string[] args)
{

Results results= new Results
{
    Data = new Data{
        Profile = new Profile {
            firstname = "John",
            lastname = "Newman"
        },
        Credit = new Credit {
           balance = "30"
        }

    }

};

string json = JsonConvert.SerializeObject(results);

Console.WriteLine(json);

}

我得到的错误是“无法初始化成员数据。它不是字段或属性。我做错了什么?

4

2 回答 2

1

试试这个:

    public class Profile
    {
        public String firstname { get; set; }
        public String lastname { get; set; }
    }

    public class Credit
    {
        public int amount { get; set; }
    }

    public class Result
    {
        public Profile profile { get; set; }
        public Credit credit { get; set; }

    }
    public class Wrapper
    {
        public Result results { get; set; }

    }

    static void Main(string[] args)
    {

        var wrapper = new Wrapper
        {
            results = new Result
            {
                profile = new Profile
                {
                    firstname = "John",
                    lastname = "Newman"
                },
                credit = new Credit
                    {
                        amount = 30
                    }
            }
        };

        string json = JsonConvert.SerializeObject(wrapper);

        Console.WriteLine(json);

    }
于 2013-10-23T10:52:49.063 回答
1

尝试这个 :

   static void Main(string[]args) {
    Base results = new Base() {
        Results = new Results() {               
            profile = new Profile() {
                firstname = "John",
                lastname = "Newman"
            },
            credit = new Credit() {
                amount = 30
            }               
        }
    };

    string json = JsonConvert.SerializeObject(results);

    Console.WriteLine(json);

    Console.ReadLine();
}

public class Base {
    public Results Results {get;set;}
}

public class Results{
    public Profile profile {get;set;}
    public Credit credit {get;set;}

}   

public class Profile{
    public String firstname {get;set;}
    public String lastname {get;set;}
}

public class Credit{
    public int amount {get;set;}
}

Class Base包装Results类以获取所需的 JSON 结构。

于 2013-10-23T11:02:37.797 回答