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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13041970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:25:50  来源:igfitidea点击:

Convert JSON response stream to string

c#.netjson

提问by Tom

I am trying to do a POST and then read the JSON response into a string.

我正在尝试执行 POST,然后将 JSON 响应读入字符串。

I believe my issue is that I need to pass my own object into DataContractJsonSerializer but I'm wondering if there is some way to just get the response into an associative array or some sort of key/value format.

我相信我的问题是我需要将我自己的对象传递给 DataContractJsonSerializer 但我想知道是否有某种方法可以将响应放入关联数组或某种键/值格式。

My JSON is formatted like: {"license":"AAAA-AAAA-AAAA-AAAA"} and my code is as follows:

我的 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);
}

采纳答案by JoshVarty

I'd strongly recommend looking into Newtonsoft.Json:

我强烈建议您查看 Newtonsoft.Json:

http://james.newtonking.com/pages/json-net.aspx

http://james.newtonking.com/pages/json-net.aspx

NuGet: https://www.nuget.org/packages/newtonsoft.json/

NuGet:https: //www.nuget.org/packages/newtonsoft.json/

After adding the reference to your project, you just include the following usingat the top of your file:

添加对项目的引用后,您只需using在文件顶部包含以下内容:

using Newtonsoft.Json.Linq;

And then within your method you can use:

然后在您的方法中,您可以使用:

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>();

回答by COLD TOLD

you can do something like this using dictionary

你可以使用字典做这样的事情

Dictionary<string, string> values = 
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

or something like this if you already know your object

或者类似的东西,如果你已经知道你的对象

var yourobject = JsonConvert.DeserializeObject<YourObject>(json);

with this tool

用这个工具

http://james.newtonking.com/projects/json/help/

http://james.newtonking.com/projects/json/help/

reference here Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

参考此处 使用 JsonConvert.DeserializeObject 将 Json 反序列化为 C# POCO 类