0

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?

9
  • is sub the above string? you'll have to parse it further? Commented Jul 6, 2018 at 12:24
  • yes sub is the string which has the value.Edited the question Commented Jul 6, 2018 at 12:24
  • other than .Spliting on new lines - have you tried parsing it differently? Commented Jul 6, 2018 at 12:25
  • No i have not tried any thing else, I am open for suggestion . Can you put a example of other approach and paste it as a answer Commented Jul 6, 2018 at 12:27
  • What is the gap between the property name and value? It looks like spaces so you're going to have to split that string by length. Commented Jul 6, 2018 at 12:30

2 Answers 2

1

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
};
Sign up to request clarification or add additional context in comments.

2 Comments

it worked like a charm. Many thanks for your help. Can you explain this s.Substring(0, 18) how did you came up with the number 18 here
Substring just takes a portion of a string. In this case we take the first 18 characters which is the left part of each line, then all the characters are the first 18 for the value.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.