2

I am writing results i return from stored procedure into json. I did it but i am not sure if there is a simpler cleaner way other than what i have. Also how can i check that it really wrote to json?

var results = mySvc.GetInfo("Environment");

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Id");
jsonWriter.WriteValue(results.Id);
jsonWriter.WritePropertyName("Head");
jsonWriter.WriteValue(results.Head);
jsonWriter.WritePropertyName("Value");
jsonWriter.WriteValue(results.Value);
jsonWriter.WritePropertyName("GuidTwo");
jsonWriter.WriteValue(results.GuidTwo);
jsonWriter.WritePropertyName("GuidOne");
jsonWriter.WriteValue(results.Guid1);
jsonWriter.WriteEndObject();
return results;
2

3 Answers 3

4

Install Json.NET and you simply do this:

var results = mySvc.GetInfo("Environment");
var json = JsonConvert.SerializeObject(results);

The inverse:

var results = JsonConvert.DeserializeObject<Result>(json);
Sign up to request clarification or add additional context in comments.

3 Comments

this worked nicely - now if i want to get the info from json in a different method how could i extract from this?
Where did <Result> come from?
Result is the class that the data is deserialised into. In your case, it will be whatever type is returned by mySvc.GetInfo()
2

try this

var results = mySvc.GetInfo("Environment");
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObj = js.Serialize(results);

1 Comment

what namespace is serialization under?
2

By using ServiceStack json serializer(it's faster than the json.net)

 Install-Package ServiceStack.Text
 using ServiceStack.Text;

 var json = results.ToJson();

3 Comments

and if i would like to extract information from Json - how will that look?
What is to consume the json?
@Masriyah Without using another class type to serialize to and from you can use JsonSerializer.DeserializeFromString<Dictionary<string, object>>(json); //not the best solution however with all the casting you'll need to do. - there must be a better way...

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.