2

I have following string in JSON

string IDS = "{\"IDS\":\"23,24,25,28\"}"

Now I need to convert this into c# string

I tried this

string id = new JavaScriptSerializer().Deserialize<string>(IDS);

I want to get back this comma separated string in a string, but it throws error

No parameterless constructor defined for type of 'System.String

Any help what to do ?

Thanks

4
  • 4
    "it throws error" is never enough detail. It's also unclear whether those backslashes are actually in the string, or whether that's a source-code representation of the string. It would really help if you'd provide a minimal reproducible example. Commented Sep 1, 2016 at 6:48
  • 1
    you want to deserialize a string into a string ? no, you dont. you're expecting an array i guess. try "var id" instead of "string id" in your second line of code you shared. Commented Sep 1, 2016 at 6:52
  • I have posted the error Commented Sep 1, 2016 at 6:52
  • 1
    @Doruk, I also tried var id, but same error Commented Sep 1, 2016 at 6:54

3 Answers 3

6

It's because your json string is a Dictionary. Try it with something like this

var result = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(IDS);
var mystring = result["IDS"];
Sign up to request clarification or add additional context in comments.

Comments

1

I prefer this solution using JSON.net:

class Program
{
    static void Main(string[] args)
    {
        string IDS = "{\"IDS\":\"23,24,25,28\"}";
        var obj = JsonConvert.DeserializeObject<MyClass>(IDS);
        Console.WriteLine(obj.IDS);
        Console.ReadLine();
    }
}

class MyClass
{
    public string IDS { get; set; }
}

1 Comment

I love to work with Newtonsofts JSON.net, +1 for suggesting it.
1

The error occurs because you are using the incorrect type string to deserialize, it should be a Dictionary as Matthias Burger mentioned. However you can use dynamic type,

string json = "{\"IDS\":\"23,24,25,28\"}";
var jobject = new JavaScriptSerializer().Deserialize<dynamic>(json );
string ids = jobject["IDS"]

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.