I'm begginer in JSON deserialize objects. I tried to use JSON.NET.
I have a hardware device which send me a JSON message like this.
{
"settings": [{
"slotid": 13,
"live": {
"values": [
{"id":1,"v":"3.5.0"},
{"id":2,"v":""},
{"id":3,"v":282827},
{"id":4,"v":127},
{"id":5,"v":127},
{"id":10,"v":7},
{"id":11,"v":1},
{"id":12,"v":22},
{"id":13,"v":1},
{"id":14,"v":1},
{"id":15,"v":0},
{"id":16,"v":2},
{"id":17,"v":0},
{"id":18,"v":0}
]
},
"presets": []
}]
}
I tried to do it exactly as in
https://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm
but something goes wrong, I suppose that it depends of building of JSON answer format.
I used code like this:
public class Product
{
public string settings {get; set;}
public string values { get; set; }
//public string presets { get; set; }
public string slotid { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
string URL = "http://10.0.0.201/api/json/controls/get?slotid=13";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json = reader.ReadToEnd();
try
{
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
}
catch(Exception E)
{
}
}
}
In json variable I keep JSON message.
I suppose that I have to build custom datatable, but how?
Regards
Ps.
I forgot to say that I need to get only "id" and "v" from JSON from values.
Related
How can I Post for example this information of below to this website "http://restapi.adequateshop.com/api/Tourist"
by C# code?
tourist_name: "dummy"
tourist_email: "test123#test.com"
tourist_location: "Paris"
static void Main(string[] args)
{
//create the constructor with post type and few data
string data = "tourist_name=Mike&tourist_email=miked123#gmail.com&tourist_location=Paris";
MyWebRequest myRequest = new MyWebRequest("http://restapi.adequateshop.com/api/Tourist", "POST", data);
//show the response string on the console screen.
string Response = myRequest.GetResponse();
}
You can put your data in a new class :
class RequestData
{
string tourist_name { get; set; }
string tourist_email { get; set; }
string tourist_location { get; set; }
}
Then you can serialize your object to JSON:
RequestData requestData = new RequestData();
requestData.tourist_name ="Mike";
requestData.tourist_email ="miked123#gmail.com";
requestData.tourist_location ="Paris";
string jsonData = JsonConvert.SerializeObject(requestData);
Then send your JSON to API
string URL="http://restapi.adequateshop.com/api/Tourist";
var jsonContent = new StringContent(jsonData,Encoding.UTF8,"application/json");
var result = client.PostAsync(URL,jsonContent).Result;
I hope this answers your question.
So I am retrieving JSON data from my site and this is my code:
The model:
class Reservations
{
public string id_reservation { get; set; }
public string spz { get; set; }
public string reservation_day { get; set; }
public string reservation_time { get; set; }
public string ip_address { get; set; }
}
The connection and parsing:
protected async void CheckReservations(string day)
{
if (CrossConnectivity.Current.IsConnected)
{
try
{
private const string Url = "Urltomysite";
private HttpClient _client = new HttpClient();
var content = await _client.GetStringAsync(Url);
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(content);
foreach (Reservations res in myData)
{
System.Console.WriteLine("Time:" + res.reservation_time);
}
}
catch (Exception e)
{
Debug.WriteLine("" + e);
}
}
}
And the JSON response from my site:
[
{
id_reservation: "39",
spz: "NRGH67L",
reservation_day: "2019-01-26",
reservation_time: "14:00",
ip_address: "192.168.137.5"
}
]
But when I try to print the reservation_time from List of the Object in the foreach I dont get any results. I am still pretty new to this and got this far from tutorials, so dont know what I am missing.
Thanx for any replies.
I suggest using a crash prone way of this
var response = await client.GetAsync(uri);
if(response.IsSuccessStatusCode)
{
var json = await responseMessage.Content.ReadAsStringAsync(); //using ReadAsStreamAsync() gives you better performance
List<Reservations> myData = JsonConvert.DeserializeObject<List<Reservations>>(json);
//do the rest jobs
}
else
{
//alert the api call failed
}
globally, I have the following object:
public class Geraet
{
public long Geraetenr { get; set; }
public int Typ { get; set; }
public string Platz { get; set; }
public string Bezeichnung { get; set; }
public int Tr { get; set; }
public string Ip { get; set; }
public string Bespielt { get; set; }
}
I populate a list of those objects, serialize them and send them via webservice:
[HttpGet]
public IHttpActionResult Get_Feedback()
{
List<Geraet> geraeteliste = null;
try
{
geraeteliste = GetSpielgeraeteFromDatabase();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
if (geraeteliste == null)
{
return Ok("No record found!");
}
else
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(geraeteliste);
return Json(json);
}
}
The data received by webservice looks like the following:
"[{\"Geraetenr\":123456789,\"Typ\":61,\"Platz\":\"1-01\",\"Bezeichnung\":\"CSII ADM430\",\"Tr\":3,\"Ip\":\"123.123.123.123\",\"Bespielt\":\"0\"},{\"Geraetenr\":987654321,\"Typ\":61,\"Platz\":\"2-12\",\"Bezeichnung\":\"M-BOX PUR+ GOLD\",\"Tr\":3,\"Ip\":\"124.124.124.124\",\"Bespielt\":\"0\"}]"
In my Xamarin App, I have the same object given above and trying to deserialize it:
private List<Geraet> GetSpielgeraeteFromWebservice()
{
List<Geraet> geraeteliste;
var request = HttpWebRequest.Create(Constants.GeraetelistServicePath);
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var json = reader.ReadToEnd();
geraeteliste = JsonConvert.DeserializeObject<List<Geraet>>(json);
}
}
return geraeteliste;
}
Unfortunately, I get an runtime error in the line geraeteliste = JsonConvert.DeserializeObject<List<Geraet>>(json); saying:
Unhandled Exception:
Newtonsoft.Json.JsonSerializationException: Error converting value "[{"Geraetenr":123456789,"Typ":61,"Platz":"1-01","Bezeichnung":"CSII ADM430","Tr":3,"Ip":"123.123.123.123","Bespielt":"0"},{"Geraetenr":987654321,"Typ":61,"Platz":"2-12","Bezeichnung":"M-BOX PUR+ GOLD","Tr":3,"Ip":"124.124.124.124","Bespielt":"0"}]" to type 'System.Collections.Generic.List`1[GroceryList.Classes.Geraet]'. Path '', line 1, position 3421.
The sending / retrieving stuff does work, otherwise error message would be in the line var json = reader.ReadToEnd(); or I wouldn't have gotten the right values in the error message. So something with the deserialization does not work.
Can anyone maybe help and tell me what is or could be the problem? Why can't he convert? It is the right order and the right values?
Best regards
I have a question about inserting a json formatted string into a json structure and having the final version be a combined JSON formatted string that can be serialized into a JSON structure. I am using the newtonsofts Json.NET
I have the following JSON structure:
public class ResponseJson
{
[JsonProperty(PropertyName = "header")]
public ResponseHeader responseHeader { get; set; }
[JsonProperty(PropertyName = "results")]
public string responseResults { get; set; }
}
public class ResponseHeader
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "version")]
public string version { get; set; }
}
In the code, I do the following:
ResponseJson responseJson = new ResponseJson();
responseJson.responseHeader = new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
};
responseJson.responseResults = resultJson;
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
resultJson is a properly formatted JSON string (in this case, an array of objects, but could be anything JSON formatted). Right now, if i execute the code, I get the following (which is expected, since "results" is declared as a string):
{
"header":
{
"name":"abcd",
"version":"1.0"
},
"results":
"[{\"data\":{\"level\":\"100\"},\"code\":{\"value\":\"JBC\",\"type\":\"ev\"},\"time\":{\"start\":\"20\",\"end\":\"101\"}}]"
}
what I do need as an output is:
{
"header":
{
"name":"abcd",
"version":"1.0"
},
"results":
[
{
"data":
{
"level":"100"
},
"code":
{
"value":"JBC",
"type":"ev"
},
"time":
{
"start":"20",
"end":"101"
}
}
]
}
While you don't explain how you create your resultJson variable, it's implied from your code that you are double-serializing your results: you compute an array of "result" classes, serialize them to a JSON string, store the string in your ResponseJson class, and them serialize that in turn. The embedded JSON string then gets escaped as per the JSON standard, which is what you are seeing.
You need to avoid double-serializing your data, for instance by using the following data model:
public class ResponseJson<T>
{
[JsonProperty(PropertyName = "header")]
public ResponseHeader responseHeader { get; set; }
[JsonProperty(PropertyName = "results")]
public T responseResults { get; set; }
}
public static class ResponseJson
{
public static ResponseJson<T> Create<T>(T responseResults, ResponseHeader responseHeader)
{
return new ResponseJson<T> { responseResults = responseResults, responseHeader = responseHeader };
}
}
public class ResponseHeader
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "version")]
public string version { get; set; }
}
Then you would do:
var results = GetResults(); // Get your result data
var responseJson = ResponseJson.Create(results, new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
});
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
If for whatever reason you must embed a previously serialized JSON string as JSON rather than as a string literal, you'll need to re-parse it back to a JToken:
string resultJson = GetResultJson(); // Get result json string.
var responseJson = ResponseJson.Create(JToken.Parse(resultJson), new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
});
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Json.NET will include the JToken in your outer JSON as nested JSON rather than as a string literal.
I have a json coming from webservice, which has a List<> element in it.
But when I try to deserialize it using Newtonsoft.Json
Response resp = JsonConvert.DeserializeObject<Response>(responseStr);
then when I fetch the list using resp.ProjectList, it throws a null pointer exception.
So the List<Project> is not getting deserialized.
Any idea what am I missing?
The response is of the form:
public Response
{
public string msg;
public List<Project> ProjectList{get; set;}
}
[DataContract]
public class Project
{
[DataMember]
public string ID {get; set;}
}
Just remove the [DataContract] and [DataMember] attributes, they do not mix well with Json.NET.
Or you can do the deserialization "manually"
var j = JToken.Parse("{ \"Msg\": \"Success\", \"ProjectList\": [ { \"ID\": \"/Date(1400120100000-0700)/\" }, { \"ID\": \"/Date(1404260520000-0700)/\" } ] } ");
var resp = new Response
{
msg = j.SelectToken("Msg").ToString(),
ProjectList = ((JArray) j.SelectToken("ProjectList")).Select(l => new Project {ID = l.SelectToken("ID").ToString()}).ToList()
};