ankur
ankur

Reputation: 4733

Create a JSON object from simple string in C#

I am getting a string as a response from my command line. I want to convert it into a json string , which i will later use to convert to a c# object.

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

tried converting it into json by below code

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

Token Class

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

    }

It Gives this error

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

.

Converted JSON

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

Any Help to convert the string into a JSON/C# object?

Upvotes: 0

Views: 203

Answers (2)

Michał Stachyra
Michał Stachyra

Reputation: 1

First of all you should parse this 'sub' string in different way. Second you should create JObject not trying serialize Array of strings.

Try this

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

Then just add correct attribute on propteries inside your model

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

Upvotes: 0

DavidG
DavidG

Reputation: 118957

It looks far simpler to forget about JSON and parse manually. For example:

//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
};

Upvotes: 1

Related Questions