开发者

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

开发者 https://www.devze.com 2023-03-12 00:18 出处:网络
I have the following model: namespace power.Storage.Models { public class Answer { public HtmlText[] Explanation { get; set; }

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 so开发者_Go百科mething 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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消