WebApi HttpClient帮助获取集合(版本.6)

时间:2012-01-12 01:57:02

标签: wcf-web-api

我正在调用WCF Data Services v3 Odata服务。 我无法在下面的示例中填写我的集合。我能够获得3个人的json字符串,但如果我尝试填充自定义集合,则该集合的count = 0。

HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

client.BaseAddress = new Uri("http://localhost:7500/Wcf1.svc/People");

HttpResponseMessage resp = client.GetAsync("").Result;

string jsonString = resp.Content.ReadAsStringAsync().Result;

List<Person> personCollection = resp.Content.ReadAsAsync<List<Person>>().Result;

jsonString里面有3个人。

personCollection的count = 0。

jsonString看起来像这样:

{"d":[
{"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(1)",
"uri":"http://localhost:7500/Wcf1.svc/People(1)",
"type":"WcfService1.Person"},
"ID":1,"Fname":"Fred","Lname":"Peters","Address1":"123 Main"},

 {"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(2)",
"uri":"http://localhost:7500/Wcf1.svc/People(2)",
"type":"WcfService1.Person"},
"ID":2,"Fname":"John","Lname":"Smith","Address1":"123 Oak"},

{"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(3)",
"uri":"http://localhost:7500/Wcf1.svc/People(3)",
"type":"WcfService1.Person"},
"ID":3,"Fname":"Tom","Lname":"Anders","Address1":"123 Hill St."}]}

我必须做错事,如果可以,请指出我的错误。

感谢。 泰伦斯

1 个答案:

答案 0 :(得分:3)

您的内容不是列表&lt; Person&gt;

将您的Json粘贴到json2csharp,然后您就会看到它。

要更好地了解您的回复内容,请下载Json Viewer - 这是您的数据的屏幕截图:

enter image description here

如您所见:人是Json根对象的属性。

如果你想使用上面的代码,Json应该看起来像这样(或者你需要访问给定结构中的数据,根据Json映射你的类):

[{"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(1)",
"uri":"http://localhost:7500/Wcf1.svc/People(1)",
"type":"WcfService1.Person"},
"ID":1,"Fname":"Fred","Lname":"Peters","Address1":"123 Main"},

 {"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(2)",
"uri":"http://localhost:7500/Wcf1.svc/People(2)",
"type":"WcfService1.Person"},
"ID":2,"Fname":"John","Lname":"Smith","Address1":"123 Oak"},

{"__metadata":{"id":"http://localhost:7500/Wcf1.svc/People(3)",
"uri":"http://localhost:7500/Wcf1.svc/People(3)",
"type":"WcfService1.Person"},
"ID":3,"Fname":"Tom","Lname":"Anders","Address1":"123 Hill St."}]}]

<强>更新

你应该能够解析你最初发布的Json:

var json = JsonValue.Parse(response.Content.ReadAsStringAsync().Result);
var arr = json["d"];
var contact1 = arr[0];
var fname = result1["Fname"];

我最近做了blog post on JsonValue and JsonArray。它是服务器端,但它应该指明你的方向。

第二次更新:

使用json2csharp.com输出中的类,您可以执行以下操作:

public class Metadata
{
    public string id { get; set; }
    public string uri { get; set; }
    public string type { get; set; }
}

public class D
{
    public Metadata __metadata { get; set; }
    public int ID { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }
    public string Address1 { get; set; }
}

public class RootObject
{
    public List<D> d { get; set; }
}

用法:

var root = resp.Content.ReadAsAsync<RootObject>().Result;
var persons = root.d;
var person1 = persons[0];