簡體   English   中英

從C#中的簡單字符串創建JSON對象

[英]Create a JSON object from simple string in C#

我從命令行得到一個字符串作為響應。 我想將其轉換為json字符串,稍后將用於轉換為ac#對象。

The string Response(sub variable has this string as value) 
Access Token      00D0E00000019dU!
Alias             accp
Client Id         SalesforceDevelopmentExperience
Connected Status  Connected
Id                00D
Instance Url      https://my.salesforce.com
Username          ankur

嘗試通過以下代碼將其轉換為json

string[] subArray = sub.Split('\n'); 
            string output = JsonConvert.SerializeObject(subArray);                       
            var result = JsonConvert.DeserializeObject<Token>(output);

代幣類

public class Token
    {
        public string AccessToken { get; set; }
        public string Alias { get; set; }

    }

它給出了這個錯誤

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Token' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1

轉換后的JSON

["Access Token      00D0E00000019dU!AQU","Alias             accp","Client Id         SalesforceDevelopmentExperience","Connected Status  Connected","Id                00D","Instance Url      https://my.salesforce.com","Username          ankur"]

將字符串轉換為JSON / C#對象有幫助嗎?

忘記JSON並進行手動解析看起來要簡單得多。 例如:

//split up the source string into name value pairs
var nameValues = sub.Split('\n')
    .Select(s => new
    {
        Name = s.Substring(0, 18).Trim(), 
        Value = s.Substring(18).Trim() 
    });

//Create the token object manually
var token = new Token
{
    AccessToken = nameValues.Single(v => v.Name == "Access Token").Value,
    Alias = nameValues.Single(v => v.Name == "Alias").Value
};

首先,您應該以不同的方式解析此“ sub”字符串。 其次,您應該創建JObject,而不是嘗試序列化字符串數組。

嘗試這個

// Splitting into string lines
var subArray = sub.Split('\n')
    .Where(x => !string.IsNullOrEmpty(x));

JObject tokenJObj = new JObject();
foreach (var oneSub in subArray)
{
// I assume that the value will be after the last empty character
    tokenJObj.Add(
        oneSub.Substring(0, oneSub.LastIndexOf(' ')).Trim(), 
        oneSub.Substring(oneSub.LastIndexOf(' ') + 1));
}
string tokenStringJson1 = tokenJObj.ToString();
// or
string tokenStringJson2 = JsonConvert.SerializeObject(tokenJObj);

然后在模型內部的屬性上添加正確的屬性

public class Token
    {
        [JsonProperty("Access Token")]
        public string AccessToken { get; set; }

        // In this property attribute is not requied
        [JsonProperty("Alias")]
        public string Alias { get; set; }
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM