json to c# deserilization - c#

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.

Related

Created Nested JSON array from JSON array

I am pretty new to JSON and C# and have created an Azure Function that ties back to Snowflake which requires a very specific type of JSON response. I would like assistance if any in turning a JSON response I'm getting to a slightly different formatted response.
{
"access_token": "access token value here" , "user": "user_val"
}
to looking like
{
"data":
[
[ 0, { "access_token" : "access token value here", "user" : "user_val" } ]
]
}
I need create a nested array with "data" as the parent and a row number response starting at 0.
Using Json.NET:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json = #"{
""access_token"": ""access token value here"" , ""user"": ""user_val""
}";
Access a = JsonConvert.DeserializeObject<Access>(json);
var accessCollection = new AccessCollection
{
Data = new List<Access> { a }
};
json = JsonConvert.SerializeObject(accessCollection, Formatting.Indented);
Console.WriteLine(json);
}
}
public class Access
{
[JsonProperty("access_token")]
public string AccessToken
{
get;
set;
}
[JsonProperty("user")]
public string User
{
get;
set;
}
}
public class AccessCollection
{
[JsonProperty("data")]
public List<Access> Data
{
get;
set;
}
}
In addition, I consider the inner array is not usual because the data type are int and object. In general, they should be of same type. Because of that, I use a single dimensional array instead.
Please modify the codes according to situation.
.NET Fiddle

Get number from API and put it in a variable

I want to get the price value which is usd in this api and put it in a variable:
https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd
I already tried this code but getting an error:
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<VECO.Coin> items = JsonConvert.DeserializeObject<List<VECO.Coin>>(jsonString);
foreach (var item in items)
{
Console.WriteLine(item.usd);
}
}
public class VECO
{
public static string VecoPriceURL = "https://api.coingecko.com/api/v3/simple/price?ids=veco&vs_currencies=usd";
public class Coin
{
public string usd { get; set; }
}
}
ERROR:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current
JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[ConsoleProgram.VECO+Coin]' because the
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or
change the deserialized type so that it is a normal .NET type (e.g. not a
primitive type like integer, not a collection type like an array or List<T>)
that can be deserialized from a JSON object. JsonObjectAttribute can also be
added to the type to force it to deserialize from a JSON object.
Path 'veco', line 1, position 8.'
Your Data Structures needs to be slightly different.
public class Veco
{
public decimal usd { get; set; }
}
public class RootObject
{
public Veco veco { get; set; }
}
Please note that Json is a not an array or List, so you need to need List<> in the JsonConvert.DeserializeObject Method as well. Instead, you need to the following.
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Example,
var jsonString = #"{'veco':{'usd':0.01558532}}";
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine($"USD Rate : {result.veco.usd}");
Output
USD Rate 0.01558532
Rewriting your method,
public static void StartGet()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(VECO.VecoPriceURL));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var item = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(item.veco.usd);
}
Update
Based on your comment, I would rewrite your method as follows. You no longer need the data structure.
public static void StartGet(string id)
{
var url = $"https://api.coingecko.com/api/v3/simple/price?ids={id}&vs_currencies=usd";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<JToken>(jsonString);
Console.WriteLine($"For {id},USD Rate : {result[id].Value<string>("usd")}");
}
Now you can use the method as follows
StartGet("veco");
StartGet("eos");
StartGet("uraniumx");
Output
For veco,USD Rate : 0.01581513
For eos,USD Rate : 2.42
For uraniumx,USD Rate : 0.890397

String to JSON to 2D Array C#

I am receiving response from httpWebRequest as a string, which is format of JSON. What I would like, is to change this string to json and then, there are two opitons
1) change json to the 2D array
2) change json to dictionary
The point is I want to have easy access to the variables.
This is a string I am receiving:
"[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6}... {\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]"
So as you can see I could have table with n rows and 3 columns (Year, Name, Val).
This is the code which I use to receive the response
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:5000/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//send request data in json format
streamWriter.Write(jsonData);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
//take data as string
var result = streamReader.ReadToEnd();
}
return null;
}
Instead of null I will return this array/dictionary.
Which way is better? Someone know how to make it? I feel lost in c#.
Thank you for help in advance!
First, to make work with JSON easier you can install Newtonsoft.Json package
Install-Package Newtonsoft.Json -Version 11.0.2
Then add using Newtonsoft.Json;
Look at this example
public class Item
{
public int Year { get; set; }
public string Name { get; set; }
public double Val { get; set; }
}
public class Program
{
public static void Main()
{
string json = "[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6},{\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]";
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach(var item in items)
{
Console.WriteLine("Year: {0}; Name: {1}; Val: {2}", item.Year, item.Name, item.Val);
}
}
}
Here I create a new class Item witch will be represents one object from array from your JSON. Then using Newtonsoft.Json deserialize json string to list of items.

Deserializing JSON with dynamic keys into certain type

I want to deserialize a JSON string into an Version object with the help of Newtonsoft.Json.
History is a dictionary of int keys and TaskObject values. The key is a dynamic number.
Here is a short example of the JSON:
[
{
"CurrentVersion": 3,
"TaskObject": {},
"History": {
"1": {},
"2": {}
},
"ObjectTypeName": "the type"
}
]
My Class
public class Version : Lib.Objects.Task
{
public int CurrentVersion { get; set; }
public Lib.Objects.Task TaskObject { get; set; }
public Dictionary<int, Lib.Objects.Task> History { get; set;}
public string ObjectTypeName { get; set; }
}
Code
string rawJSON;
using (var wc = new WebClient())
rawJSON = wc.DownloadString(uri);
var version = JsonConvert.DeserializeObject<Objects.Version>(rawJSON); //throws a JsonSerializationException
But I get an exception
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Any ideas how to fix this, so I can deserialize the JSON to a Version object?
Edit
Turning out that I was receiving a JSON array, so I've edited my example.
As an alternative, you can access this using the JObject
var jsonString = "{\"CurrentVersion\": 3,\"TaskObject\": { },\"History\": {\"1\": { },\"2\": { }},\"ObjectTypeName\": \"the type\"}";
I've "escaped" the back slashes in my example.
var jo = JObject.Parse(jsonString);
This seems to deserialize ok. Then I can access the properties via the below
jo["CurrentVersion"].ToString()
jo["TaskObject"].ToString()
Hope that helps
If you declare you lib.objects.task as object, it will work.
Maybe it's enough in your case
I've found a solution:
string rawJSON;
using (var wc = new WebClient())
rawJSON = wc.DownloadString(uri);
var versions = new List<Objects.Version>();
foreach (var jToken in JArray.Parse(rawJSON))
versions.Add(JsonConvert.DeserializeObject<Objects.Version>(jToken.ToString()));

C#.net Getting values from json

I need to use some JSON data with a C# application, but i can't figure a way of getting the data.
I'm using SOCKET.IO, and here is a sample of a raw json string that is recieved
`socket.On("recieved", (data) =>
{
MessageBox.Show(data.Json.ToJsonString());
//outputs : {'name':'received','args':[{'data':'somedata'}]}
//get values from data
}`<br>
and i need to retrieve the value of 'data'
Look at the examples in the SocketIO4Net archive.
Define a class
using Newtonsoft.Json;
namespace TestProject
{
[JsonObject(MemberSerialization.OptIn)]
public class JSonData
{
[JsonProperty]
public string data { get; set; }
public JSonData()
{
}
public string ToJsonString()
{
return JsonConvert.SerializeObject(this);
}
public static JSonData Deserialize(string jsonString)
{
return JsonConvert.DeserializeObject<JSonData>(jsonString);
}
}
}
And after you get data like this :
JSonData JData = data.Json.GetFirstArgAs<JSonData>();
Ok i got that working, but if i want all args in JSON string {data:"somedata",anotherdata:'someanotherdata'} and get 'anotherdata', i tried `
JSonData part = data.Json.GetArgsAs();
Sorry for the double answers, but this did it for me
private Newtonsoft.Json.Linq.JObject get_data(SocketIOClient.Messages.JsonEncodedEventMessage data)
{
var inputdata = data;
dynamic jsondata = inputdata.GetArgsAs<Object>();
jsondata = jsondata[0];
return jsondata;
}
and then just do
dynamic json = get_data(data.Json);

Categories

Resources