【问题标题】:How to convert string to JSON object in .NET? [duplicate]如何在 .NET 中将字符串转换为 JSON 对象? [复制]
【发布时间】:2019-08-15 21:15:16
【问题描述】:

我对编码完全陌生,如果我对通过 youtube 视频学到的这段代码做出任何愚蠢的假设,请多多包涵。我正在通过 REST API 查询 Salesforce,并且我的响应已转换为字符串。第 1 部分:我想以漂亮的 JSON 格式打印它,第 2 部分:将 JSON 数据存储到一个对象中。

我还没有尝试过 zilch,但我正在查看这个论坛上的一些以前的答案。

        HttpClient apiCallClient = new HttpClient();
        String restCallURL = serviceUrl + "/services/data/v45.0/query?q=SELECT+Id,PAL_ID__c+FROM+Account";
        HttpRequestMessage apirequest = new HttpRequestMessage(HttpMethod.Get, restCallURL);
        apirequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        apirequest.Headers.Add("authorization","Bearer " + authToken);
        HttpResponseMessage apiCallResponse = await apiCallClient.SendAsync(apirequest);
        String requestresponse = await apiCallResponse.Content.ReadAsStringAsync();
        Console.WriteLine(requestresponse);
        Console_textBox.AppendText(requestresponse);

只需要在我的控制台上使用 Pretty Print JSON 并将该数据存储在一个对象中。

【问题讨论】:

标签: c# json json.net dotnet-httpclient


【解决方案1】:

您可以创建一个简单的类来保存 Salesforce 响应,例如:

public class SalesforceListResponse<T>
{
    [JsonProperty("totalSize")]
    public string TotalSize { get; set; }

    [JsonProperty("done")]
    public bool Done { get; set; }

    [JsonProperty("nextRecordsUrl")]
    public string NextRecordsUrl { get; set; }

    [JsonProperty("records")]
    public T[] Records { get; set; }
}

并制作一个简单的类来保存帐户:

public class Account
{
    public string Id { get; set; }

    public string PAL_ID__c { get; set; }

    ⋮
}

然后反序列化它:

var salesforceResponse = JsonConvert.DeserializeObject<SalesforceListResponse<Account>>(requestresponse );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2016-10-05
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多