views:

56

answers:

2

Trying to get an object out of str1=X&str2=Y using Newtonsoft.Json

Getting: "Unexpected character encountered while parsing value: s. Line 1, position 1."

Am i way off expecting this to work?

public class MyTest 
{
    public string str1 { get; set; }
    public string str2 { get; set; }
}

public MyTest GetJson()
{
        data = "str1=X&str2=Y";
        JsonSerializerSettings jss = new JsonSerializerSettings();
        jss.MissingMemberHandling = MissingMemberHandling.Error;
        jss.ObjectCreationHandling = ObjectCreationHandling.Reuse;
        MyTest myTest = JsonConvert.DeserializeObject<MyTest>(data, jss);
}
+3  A: 

Yes, you're way off. json looks more like this:

{"str1":"x","str2":"y"}

See www.json.org for more information.

Edit

To convert a query string to json:

var queryString = "str1=X&str2=Y";
var queryParams = HttpUtility.ParseQueryString(queryString);

var jsonObject = new JObject(from k in queryParams.AllKeys 
                             select new JProperty(k, queryParams[k]));

To convert a json string to an object:

MyTest test = JsonConvert.DeserializeObject<MyTest>(jsonObject.ToString());

To convert an object to json:

var test = JsonConvert.SerializeObject( new MyTest{str1 = "X", str2 = "Y"});
StriplingWarrior
One minor nit, proper JSON always encapsulates the key names in double quotes: `{"str1":"x","str2":"y"}` Though this is not always enforced. Your example is a javascript object literal which while similar, is not the same.
John Sheehan
while that's a valid Javascript object, it's not valid JSON. JSON requires keys to be quoted as well, you'd have this:`{"str1":"x","str2":"y"}`
bluesmoon
Thanks, guys. Fixed the response.
StriplingWarrior
yeah i know that, I am trying to transform the string into json. Any ideas?
saarpa
@saarpa: See my updated answer
StriplingWarrior
+2  A: 

That's a query string, not a JSON string.
You can parse it using HttpUtility.ParseQueryString, which returns a NameValueCollection.

SLaks
which leaves me about the same place, how do i convert NameValueCollection into json?
saarpa