0

I have a List that is converted to a string for JSON parsing. I need to replace 0 values with the word "null" since the API that I'm using accepts it rather than leaving it blank it the list.

I tried string replace "0," with "null," however this will not work when the end of the list value is 0.

public List<double> Message { get; set; }

public string jsonMessage
    get {
        string test = "";
    if (this.Message!= null && this.Message.Count > 0)
    {
        test = String.Join(",", this.Message).Replace("0,","null,")
    }
    return test; 
}
7
  • What has this got to do with JavaScript? Commented May 16, 2019 at 5:08
  • can you provide test data.. or values present in Message Commented May 16, 2019 at 5:10
  • Why dont you replace the values in the list before creating the string? Commented May 16, 2019 at 5:11
  • 4
    Are you sure that's JSON? Commented May 16, 2019 at 5:14
  • You don't need the message count check; string join returns an empty string if there are zero elements in your list Commented May 16, 2019 at 5:27

2 Answers 2

5

I believe this should accomplish what you're describing:

test = string.Join(",", Message.Select(n => n == 0 ? "null" : n.toString());
Sign up to request clarification or add additional context in comments.

Comments

2

I'm not sure why you have called that property jsonMessage, do you trying to construct json by hand or something? But anyway, you can simply do:

test = String.Join(",", this.Message.Select(s => s == 0 ? "null" : s.ToString()));

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.