如何返回WebRequest多维JSON?

时间:2018-03-06 20:57:39

标签: c# json http

这是我目前的代码:

    public string Get(int id)
    {
        HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
        HttpWebRequest.DefaultCachePolicy = policy;
        HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some URl that returns a json");
        request.Method = WebRequestMethods.Http.Get;
        request.Accept = "application/json";
        request.ContentType = "application/json; charset=utf-8";
        request.MaximumAutomaticRedirections = 4;
        request.MaximumResponseHeadersLength = 4;
        request.Credentials = CredentialCache.DefaultCredentials;
        request.CachePolicy = noCachePolicy;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        return // RESPONSE AS JSON???;
    }

    public class Persons
    {
        public string index { get; set; }
        public string thing { get; set; }
        public string name { get; set; }
        public string title { get; set; }
    }

我想将响应作为多维json返回..

我该怎么做? 它应该是这样的:

{"data":{"Person1":{"id":1,"thing":"thingOne","name":"personOneName","title":"personOneTitle"},"Person2":{"id":2,"thing":"thingTwo","name":"personTwoName","title":"personTwoTitle"}}

1 个答案:

答案 0 :(得分:0)

请务必将以下指令添加到您的班级

using Newtonsoft.Json; 

此代码会将您的回复转换为对象。

Stream newStream = response .GetResponseStream();
StreamReader sr = new StreamReader(newStream);    
var result = sr.ReadToEnd();    

//this will turn your response into a c# object of RootObject Type
//only do this is you're sure it will Deserialize into a RootObject type. 
var convertResponseToObj= JsonConvert.DeserializeObject<RootObject>(result); 

//if you want to see what's being returned by your endpoint 
//without turning it into a RootObject type then remove <RootObject> see line below.
//doing this may help you Deserialize the response correctly. 

//var convertResponseToObj= JsonConvert.DeserializeObject(result); 

public class Persons
{
     public string index { get; set; }
     public string thing { get; set; }
     public string name { get; set; }
     public string title { get; set; }
}

public class RootObject
{
     public List<Person> data {get; set;}
}

如果您想对该c#对象进行一些操作然后将其转换为JSON,您可以这样做:

string myJson = JsonConvert.SerializeObject(someCSharpObj); //this will turn your c# object into json