How read value from json with out using json.net - c#

I got a response from a webservice as shown below
{
"header": {
"sourceId": "1002",
"mndAction": "CREATE",
"msgId": "msg10022",
"errMsg": null,
"txnStatusFlg": "1",
"successMsg": "SUCCESS"
},
"response": {"responseString": "Required Data"}
}
I want to get the value of responseString from the above json data.
For the response
{"Status":"success","DocRepoId":225,"Details":"success",
"ErrorCode":"","responseString": "Required Data"}
I used the code
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.Deserialize<Dictionary<string, string>>
(response);
string responseString= someObject["responseString"].ToString();
to get the value of responseString but in this case its showing error.
I'm looking for a solution without using json.net or anything similar.
My project is on .net version 3.5.

Here it goes an example of what i told you in comment.
Using this classes:
class Test
{
public Response Response { get; set; }
}
class Response
{
public string ResponseString { get; set; }
}
You can get what you want with this code:
JavaScriptSerializer s = new JavaScriptSerializer();
string json = #"{
""header"": {
""sourceId"": ""1002"",
""mndAction"": ""CREATE"",
""msgId"": ""msg10022"",
""errMsg"": null,
""txnStatusFlg"": ""1"",
""successMsg"": ""SUCCESS""
},
""response"": { ""responseString"": ""Required Data""}
}";
Test t = s.Deserialize<Test>(json);
var responseString = t.Response.ResponseString;

Related

Getting the query result of LUIS

I have created a LUIS account and did everything that was needed.
I have written the following code and got the result from LUIS.
I need to know how to save the result of my query to a variable, using which I would like to search the database or web.
Below is the code..
static async void MakeRequest(string qz) {
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
var luisAppId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var endpointKey = "XXXXXXXXXXXX";
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", endpointKey);
// The "q" parameter contains the utterance to send to LUIS
queryString["q"] = qz;
// These optional request parameters are set to their default values
queryString["timezoneOffset"] = "0";
queryString["verbose"] = "false";
queryString["spellCheck"] = "false";
queryString["staging"] = "false";
var endpointUri = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + luisAppId + "?" + queryString;
var response = await client.GetAsync(endpointUri.);
var strResponseContent = await response.Content.ReadAsStringAsync();
// Display the JSON result from LUIS
Console.WriteLine(strResponseContent.ToString());
}
And also here is the query result.
{
"query": "the best resturant in Paris",
"topScoringIntent": {
"intent": "city",
"score": 0.436210483
},
"entities": [
{
"entity": "paris",
"type": "city",
"startIndex": 22,
"endIndex": 26,
"score": 0.7153605
}
]
}
Now I want to save this
"entity": "paris",
"type": "city",
to a variable. Kindly guide me as I am completely new to MS LUIS.
example:
string result = "paris" /// which the value should be taken from luis query
string type = "city" /// which the value should be taken from luis query
One option is to reference Newtonsoft.Json NuGet package to your project.
Then you may create two classes (feel free to change the name)
public class LuisExtractionLuisResult
{
public List<LuisEntity> entities { get; set; }
}
public class LuisEntity
{
public string entity { get; set; }
public string type { get; set; }
}
Then one example of use is
var target = JsonConvert.DeserializeObject<LuisExtractionLuisResult>(strResponseContent);
requested values are then retrieved by:
string result = target.entities[0].entity;
string type = target.entities[0].type;
And one more question, if in the query we have more than one entities.
how to get that as well?
foreach(LuisEntity oneEntity in target.entities)
{
string result oneEntity.entity;
string type = oneEntity.type;
}

Deserialize JSON with variable property name and nested list to object

I have a bunch of API which generates the following 2 kinds of reply in response body:
{ "error": null, "object_type": { /* some object */ } }
{ "error": null, "object_type": [{ /* some object */ }, { /* some object */ }, ...] }
While I have a class corresponding to the object structure, I want to deserialize the API endpoints directly into either an object of the class or a List<class>, without creating some "result" classes to match the response JSON structure. Is this possible?
For example there is 2 API:
/api/getAllCompanies
returns
{ "error": null, "company": [ { "name": "Microsoft", "country": "US" }, { "name": "Apple", "country": "US" } ]
while
/api/getUserCompany
returns
{ "error": null, "company": { "name": "Microsoft", "country": "US" } }
I have a class in code:
public class Company {
string Name { get; set; }
string Country { get; set; }
}
How can I directly deserialize the data into a Company object or a List<Company> without creating a bunch of other class?
(The JSON property name (company) is known so don't need to extract it elsewhere.)
I've been trying to first deserialize the response JSON into an ExpandoObject then copy the properties to an instance of destination class using the code here then convert it using the following code, but this seems not to work with lists.
private static async Task<T> GetApiObject<T>(string api, string extractedObjName) where T: class, new()
{
var retstr = await /* get API response as string */;
dynamic retobj = JsonConvert.DeserializeObject<ExpandoObject>(retstr, new ExpandoObjectConverter());
var ret = new T();
Mapper<T>.Map((ExpandoObject)((IDictionary<string, object>)retobj)[extractedObjName], ret);
return ret;
}
You can use JObejct to extract the information you need before deserialize it into the object.
var str = "{ \"error\": null, \"company\": [{ \"name\": \"Microsoft\", \"country\": \"US\" } ,{ \"name\": \"Apple\", \"country\": \"US\" } ]}";
var temp = JObject.Parse(str).GetValue("company");
var companies = temp.Select(x => x.ToObject<Company>()).ToList();
Same goes for /api/getUserCompany
var str = "{ \"error\": null, \"company\": { \"name\": \"Microsoft\", \"country\": \"US\" } }";
var temp = JObject.Parse(str).GetValue("company");
var company = temp.ToObject<Company>();

json to c# deserilization

I want to convert this JSON return from php file into c#. But as a newbie don't know how, please help.
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
The above JSON is returned from my PHP file.
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
List<Response> json ;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
The Classes I am using are:
public class Response
{
public string user_id { get; set; }
public string crtloc_lat { get; set; }
public string crtloc_lng { get; set; }
}
public class RootObject
{
public List<Response> response { get; set; }
}
I am getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[afterall.Response]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
The following line is wrong based on your sample JSON.
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
Try changing it to:
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
Edit:
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
RootObject json;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
rewrite the following line :
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
as
json = JsonConvert.DeserializeObject<Response>(stream.ReadToEnd());
From your testlink in the comment of your post. Your response is not:
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
as you post but rather:
connected{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"
}]
}
This is not corresponding to your sample code. Remove the
connected{ }
wrapping or return correct json for a connected object (whatever the connect is). If you remove the wrapping it should work as #Dietz posted.

How can I catch a specific value with JSON Deserialize?

I catch a JSON with .NET:
string result = json_serializer.Deserialize(myJSON);
well the structure of JSON is such as:
result
data[0]
user
bio
name
nickname
data[1]
user
bio
name
nickname
data[2]
user
bio
name
nickname
and I'd like to get only the first nickname (as string) that have some value: I mean, it is not null and is not empty.
How can I do it?
From what I understand from your question, you would want something like this,
public string FirstUserNickname(string JsonUserInfo)
{
JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
ResultData Results = JsonSerializer.Deserialize<ResultData>(JsonUserInfo);
foreach (UserInfo UserInfo in Results.result)
{
if (string.IsNullOrEmpty(UserInfo.nickname))
return UserInfo.nickname;
}
return null;
}
public class ResultData
{
public List<UserInfo> result;
}
public class UserInfo
{
public string bio;
public string name;
public string nickname;
}
This will achieve your goal and is a strongly typed approach, using the JavaScriptSerializer class from the System.Web.Extensions assembly, more info can be found here.
You can use Linq to JSON (search NuGet for Newtonsoft Json). Assume your JSON looks like:
{ "result": [ { "bio": "foo", "name": "Robin", "nickname": "Moll" },
{ "bio": "bar", "name": "Ted", "nickname": "DoctorZ" },
{ "bio": "moo", "name": "Barney", "nickname": "Wait4it" } ]
}
Then getting name of first user:
JObject jo = JObject.Parse(json);
var name = (string)jo["result"][0]["name"]; // Robin
Of course if it is possible that you will not have any users, then you should verify that user exists:
JObject jo = JObject.Parse(json);
var user = jo["result"].FirstOrDefault();
if (user != null)
name = (string)user["name"];
Using Linq to JSON you can deserialize to .net objects, like so:
Result deserializedResult = JsonConvert.DeserializeObject<Result>(json);
After that you can use LINQ to query the objects:
User nicknameduser = deserializedResult.Users
.FirstOrDefault(r => !string.IsNullOrEmpty(r.nickname))
if (nicknameduser == null) return null;
return nicknameduser.nickname;

How to create JSON string in C#

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?
Using Newtonsoft.Json makes it really easier:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
Documentation: Serializing and Deserializing JSON
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.
//Create my object
var myData = new
{
Host = #"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string jsonData = JsonConvert.SerializeObject(myData);
//Print the Json object
Console.WriteLine(jsonData);
//Parse the json object
JObject jsonObject = JObject.Parse(jsonData);
//Print the parsed Json object
Console.WriteLine((string)jsonObject["Host"]);
Console.WriteLine((string)jsonObject["UserName"]);
Console.WriteLine((string)jsonObject["Password"]);
Console.WriteLine((string)jsonObject["SourceDir"]);
Console.WriteLine((string)jsonObject["FileName"]);
This library is very good for JSON from C#
http://james.newtonking.com/pages/json-net.aspx
This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.
public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
{
serializer.WriteObject(writer, value);
}
return encoding.GetString(stream.ToArray());
}
}
If you need complex result (embedded) create your own structure:
class templateRequest
{
public String[] registration_ids;
public Data data;
public class Data
{
public String message;
public String tickerText;
public String contentTitle;
public Data(String message, String tickerText, string contentTitle)
{
this.message = message;
this.tickerText = tickerText;
this.contentTitle = contentTitle;
}
};
}
and then you can obtain JSON string with calling
List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");
string json = new JavaScriptSerializer().Serialize(request);
The result will be like this:
json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"
Hope it helps!
You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?
If you want to avoid creating a class and create JSON then Create a dynamic Object and Serialize Object.
dynamic data = new ExpandoObject();
data.name = "kushal";
data.isActive = true;
// convert to JSON
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
Read the JSON and deserialize like this:
// convert back to Object
dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
// read a particular value:
output.name.Value
ExpandoObject is from System.Dynamic namespace.
If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.
If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.
Encode Usage
Simple object to JSON Array EncodeJsObjectArray()
public class dummyObject
{
public string fake { get; set; }
public int id { get; set; }
public dummyObject()
{
fake = "dummy";
id = 5;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
sb.Append(id);
sb.Append(',');
sb.Append(JSONEncoders.EncodeJsString(fake));
sb.Append(']');
return sb.ToString();
}
}
dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();
dummys[0].fake = "mike";
dummys[0].id = 29;
string result = JSONEncoders.EncodeJsObjectArray(dummys);
Result:
[[29,"mike"],[5,"dummy"]]
Pretty Usage
Pretty print JSON Array PrettyPrintJson() string extension method
string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();
Results is:
[
14,
4,
[
14,
"data"
],
[
[
5,
"10.186.122.15"
],
[
6,
"10.186.122.16"
]
]
]
The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.
I've found that you don't need the serializer at all. If you return the object as a List.
Let me use an example.
In our asmx we get the data using the variable we passed along
// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id)
{
var data = from p in db.property
where p.id == id
select new latlon
{
lat = p.lat,
lon = p.lon
};
return data.ToList();
}
public class latlon
{
public string lat { get; set; }
public string lon { get; set; }
}
Then using jquery we access the service, passing along that variable.
// get latlon
function getlatlon(propertyid) {
var mydata;
$.ajax({
url: "getData.asmx/GetLatLon",
type: "POST",
data: "{'id': '" + propertyid + "'}",
async: false,
contentType: "application/json;",
dataType: "json",
success: function (data, textStatus, jqXHR) { //
mydata = data;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
return mydata;
}
// call the function with your data
latlondata = getlatlon(id);
And we get our response.
{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
Include:
using System.Text.Json;
Then serialize your object_to_serialize like this:
JsonSerializer.Serialize(object_to_serialize)

Categories

Resources