Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将JSON响应流转换为字符串_C#_.net_Json - Fatal编程技术网

C# 将JSON响应流转换为字符串

C# 将JSON响应流转换为字符串,c#,.net,json,C#,.net,Json,我试图写一篇文章,然后将JSON响应读入字符串 我认为我的问题是我需要将自己的对象传递到DataContractJsonSerializer中,但我想知道是否有某种方法可以将响应传递到关联数组或某种键/值格式中 我的JSON格式为:{“license”:“AAAA-AAAA-AAAA-AAAA”},我的代码如下: using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, em

我试图写一篇文章,然后将JSON响应读入字符串

我认为我的问题是我需要将自己的对象传递到DataContractJsonSerializer中,但我想知道是否有某种方法可以将响应传递到关联数组或某种键/值格式中

我的JSON格式为:{“license”:“AAAA-AAAA-AAAA-AAAA”},我的代码如下:

using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email)))
{
   string output = new StreamReader(response).ReadToEnd();
   response.Close();

   DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string));
   MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
   string results = json.ReadObject(ms) as string;

   licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null);
}

我强烈建议查看Newtonsoft.Json:

努吉:

将引用添加到项目后,只需在文件顶部使用包含以下内容:

using Newtonsoft.Json.Linq;
然后在您的方法中,您可以使用:

var request= (HttpWebRequest)WebRequest.Create("www.example.com/ex.json");
var response = (HttpWebResponse)request.GetResponse();
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();

var json = JObject.Parse(rawJson);  //Turns your raw string into a key value lookup
string license_value = json["license"].ToObject<string>();
var request=(HttpWebRequest)WebRequest.Create(“www.example.com/ex.json”);
var response=(HttpWebResponse)request.GetResponse();
var rawJson=newstreamreader(response.GetResponseStream()).ReadToEnd();
var json=JObject.Parse(rawJson)//将原始字符串转换为键值查找
字符串license_value=json[“license”].ToObject();

您可以使用字典执行类似操作

Dictionary<string, string> values = 
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
字典值=
反序列化对象(json);
或者类似的东西,如果你已经知道你的目标

var yourobject = JsonConvert.DeserializeObject<YourObject>(json);
var yourobject=JsonConvert.DeserializeObject(json);
用这个工具

此处引用

Newtonsoft JSON可以反序列化到字典。。它可以很容易地导航。我相信其他的回答也行,但这正好让我达到了我想要达到的目的。另外,我自己也在安装JSON NET dll,这会导致错误,我强烈建议在Visual Studio中使用NUGET安装程序扩展。