从C#中的简单字符串创建JSON对象

时间:2018-07-06 12:22:00

标签: c# json

我从命令行得到一个字符串作为响应。我想将其转换为json字符串,以后将用于转换为c#对象。

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#对象?

2 个答案:

答案 0 :(得分:1)

忘记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
};

答案 1 :(得分:0)

首先,您应该以不同的方式解析此“ 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; }
    }