0

I am using Json.NET to convert a json string to a .net object, i am using the next code which i got from this answer:

dynamic answer = JsonConvert.DeserializeObject(responseString);
Console.WriteLine(answer.ToString());
Console.WriteLine(answer["db"]);

The json string is this one:

[
   {
      "db":"6-y4XlvtqzR.sqlite",
      "users":"INSERT INTO users (id, first_name, last_name, password, email, cel, level) VALUES (17,a,b,f7a9e,[email protected],2,3),(29,c,d,7c4a8d,[email protected],1,4)"
   }
]

The problem is that the application crashes on the third line of my c# code above, and the message error is the next:

A first chance exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll

What is the probem with my code? is my json string wrong? or how can i get the json object right?

The funny thing about this is that the second line of the c# code is executed fine and it prints the right string.

2
  • 3
    answer is an array Commented Dec 10, 2015 at 0:38
  • You are right, i set Console.WriteLine(answer[0]["db"]); and everything worked Commented Dec 10, 2015 at 0:40

2 Answers 2

0

Your responsestring should be formatted properly like this,

"{\"db\":\"6-y4XlvtqzR.sqlite\",\"users\":\"INSERT INTO users (id, first_name, last_name, password, email, cel, level) VALUES (17,a,b,f7a9e,[email protected],2,3),(29,c,d,7c4a8d,[email protected],1,4)\"}"

I created following sample and monitored the Json result for the object. Hope this will help.

class Program
{

    class TestClass
    {
        public string db { get; set; }
        public string users { get; set; }

    }


    static void Main(string[] args)
    {
        TestClass ts = new TestClass();
        ts.db = "6-y4XlvtqzR.sqlite";
        ts.users =
            "INSERT INTO users (id, first_name, last_name, password, email, cel, level) VALUES (17,a,b,f7a9e,[email protected],2,3),(29,c,d,7c4a8d,[email protected],1,4)";

        string json = JsonConvert.SerializeObject(ts);
        dynamic answer = JsonConvert.DeserializeObject(json);
        Console.WriteLine(answer.ToString());
        Console.WriteLine(answer["db"]);

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

Comments

0

It's possible to do it with a type specified, such as (assuming ObjectType is the desired return type):

var deserializedObject = JsonConvert.DeserializeObject<ObjectType>(responseString);

And why did you use dynamic?

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.