Resolved How do i cast a string type to a class type ?

karcs

New member
Joined
Oct 10, 2022
Messages
2
Programming Experience
Beginner
here is the ERROR MESSAGE:- Unable to cast object of type 'System.String' to type 'query'
C#:
 public static Xxl.Query QueryBySize(string SizeNo)
        {
            Query result = new Query();
            result.SizeInfo.SizeCode = "Xxl";
            Xxl.Query result1 = new Xxl.Query()
            {
                SIZE = SizeNo
            };
         
            JsonSerializerOptions options = new JsonSerializerOptions
            {
                IgnoreNullValues = true
            };
            string str = JsonSerializer.Serialize<Xxl.Query>(result1, options);
            Console.WriteLine("Retrieved Details: " + str);
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            result.Data.Content = Convert.ToBase64String(bytes);
            Xxl.Query xxl = (Xxl.Query)QueryRequest(result );

            return xxl;
        }
//second code from another file Name: Xxl.cs
C#:
 public class Query
    {
        [JsonPropertyName("itemName")]
        public ItemName ItemName { get; set; }

        [JsonPropertyName("result")]
        public string Result { get; set; }

        public Query()
        {
            ItemName = new ItemName();
        }
    }
}
 
Last edited by a moderator:
You don't. A cast can't change the type of an object. You can't cast something as a type that it isn't. If that QueryRequest method returns a string then that's what you've got. If you want a new Query object then you need to create a new object of that type. It's hard to say exactly what you should do because I don't know what that method is or exactly what you expect the result to be.
 
You don't. A cast can't change the type of an object. You can't cast something as a type that it isn't. If that QueryRequest method returns a string then that's what you've got. If you want a new Query object then you need to create a new object of that type. It's hard to say exactly what you should do because I don't know what that method is or exactly what you expect the result to be.
Got it solved. it turns out there was nothing wrong with my code. The issue was with one of the dependencies of the System.text.json.dll library called system.numeric.vectors.dll ,once i added it to the project i stopped getting the exception.Thanks for the effort
 

Latest posts

Back
Top Bottom