SeanMcD
SeanMcD

Reputation: 1

How can I convert HtmlText to a normal string in c#

I have the following model:

namespace power.Storage.Models
{
    public class Answer
    { 
        public HtmlText[] Explanation { get; set; }
        public string[] ImageFile { get; set; }
    }

    public class HtmlText { 
        [AllowHtml]
        public string TextWithHtml { get; set; } 
    }
}

Now I want to be able to take the data from answer and do the following:

String[] _code_explanation = null;
_code_explanation = 
 (string) JSON.FromJSONString<Answer>(_code.AnswersJSON).Explanation;

But it's not working. It says "can't convert HtmlText to string

Is there something I'm missing? I thought all I would need to do was to add (string) before the JSON...

Here's the code for JSON

    public static T FromJSONString<T>(this string obj)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            T ret = (T)ser.ReadObject(stream);
            return ret;
        }
    }

The following half works:

HtmlText[] _code_explanation = null;
    _code_explanation = 
     (string) JSON.FromJSONString<Answer>(_code.AnswersJSON).Explanation;

It gives me an array of HtmlText but then I am not sure how to convert this into a simple array of strings.

Upvotes: 0

Views: 271

Answers (3)

Peter Olson
Peter Olson

Reputation: 142921

You can decode HtmlText with with the HttpUtility.HtmlDecode method. It cannot be directly cast to a string.

Upvotes: 1

Jodrell
Jodrell

Reputation: 35706

HTMLText does not have a cast operator to String, explicit or implicit.

Upvotes: 2

Brian Dishaw
Brian Dishaw

Reputation: 5825

I think you want to do something like this assuming teh Explanation is of type HtmlText

String[] _code_explanation = null;
_code_explanation = 
   JSON.FromJSONString<Answer (_code.AnswersJSON).Explanation.TextWithHtml;

Upvotes: 0

Related Questions