0

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.

3
  • I do not know the answer to this particular question, but usually you do not cast to string, instead you call the .ToString() method JSON.FromJSONString<Answer>(_code.AnswersJSON).Explanation.ToString(); might work? Commented Jun 8, 2011 at 12:27
  • What implementation of JSON is this? Commented Jun 8, 2011 at 12:36
  • The .ToString() seems like it might work but the problem is that The ouput is an array. What I need is an ToStringArray :-( Commented Jun 8, 2011 at 12:53

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

But where can I put this? First I have to put the data into an array of something and what I am getting back is an array of HtmlText
0

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;

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.