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

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

最新更新