5

I am trying to do a POST and then read the JSON response into a string.

I believe my issue is that I need to pass my own object into DataContractJsonSerializer but I'm wondering if there is some way to just get the response into an associative array or some sort of key/value format.

My JSON is formatted like: {"license":"AAAA-AAAA-AAAA-AAAA"} and my code is as follows:

using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email)))
{
   string output = new StreamReader(response).ReadToEnd();
   response.Close();

   DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string));
   MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
   string results = json.ReadObject(ms) as string;

   licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null);
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Tom
  • 288
  • 1
  • 2
  • 15
  • The Newtonsoft JSON can deserialize to Dictionary .. and it can be navigated rather easily. –  Oct 24 '12 at 02:01

2 Answers2

18

I'd strongly recommend looking into Newtonsoft.Json:

http://james.newtonking.com/pages/json-net.aspx

NuGet: https://www.nuget.org/packages/newtonsoft.json/

After adding the reference to your project, you just include the following using at the top of your file:

using Newtonsoft.Json.Linq;

And then within your method you can use:

var request= (HttpWebRequest)WebRequest.Create("www.example.com/ex.json");
var response = (HttpWebResponse)request.GetResponse();
var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();

var json = JObject.Parse(rawJson);  //Turns your raw string into a key value lookup
string license_value = json["license"].ToObject<string>();
c32hedge
  • 785
  • 10
  • 19
JoshVarty
  • 9,066
  • 4
  • 52
  • 80
  • 3
    I'm sure the other responses work, but this got me exactly where I was trying to go. Also, I was installing the JSON NET dll myself and that was causing errors, I highly recommend using the NUGET installer extension in Visual Studio. – Tom Oct 25 '12 at 21:52
1

you can do something like this using dictionary

Dictionary<string, string> values = 
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

or something like this if you already know your object

var yourobject = JsonConvert.DeserializeObject<YourObject>(json);

with this tool

http://james.newtonking.com/projects/json/help/

reference here Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Community
  • 1
  • 1
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52