I am creating a project of Windows Forms Application using C#
I want to show all information(like CityName,CountryCode, etc in different Label) related to IP Address that is on my TextBox.
I already read many article about JsonConvert and I don't want to use JsonConvert.
here is my c# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace GetIPinfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<LocaionInfo1> locations = new List<LocaionInfo1>();
string url = string.Format("http://ipinfo.io/" + txtip.Text);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);
locations.Add(location);
}
if (locations.Count > 0)
{
foreach (LocaionInfo1 loc in locations)
{
label9.Text = loc.CityName;
label10.Text = loc.CountryCode;
label11.Text = loc.CountryName;
}
}
}
public class LocaionInfo1
{
public string IPAddress { get; set; }
public string CountryName { get; set; }
public string CountryCode { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ZipCode { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string TimeZone { get; set; }
}
}
}
The problem is that when i Debug this code and Enter IP in my TextBox and then click on Submit Button
My LocaionInfo1 location = new JavaScriptSerializer().Deserialize<LocaionInfo1>(json);
is NULL values.
JSON Data is:
{
"ip": "182.69.151.41",
"hostname": "abts-north-dynamic-041.151.69.182.airtelbroadband.in",
"city": null,
"country": "IN",
"loc": "20.0000,77.0000",
"org": "AS24560 Bharti Airtel Ltd., Telemedia Services"
}
So please help to get these all values.
I am using Visual Studio 2012.
So I can't actually try this because I'm on mobile but for the actual JSON you'd have to add a "/json" to the link
string url = string.Format("http://ipinfo.io/" + txtip.Text + "/json");
You need to help json.net out a bit by giving some mapping by using an attribute on your object properties:
public class LocaionInfo1
{
[JsonProperty(PropertyName = "ip")]
public string IPAddress { get; set; }
....
}
Your property names are inconsistent. For example, in the JSON you have "city" but in your object it is "CityName." How is the deserializer supposed to know how to map them?
Related
This question already has answers here:
Parse JSON response where the object starts with a number in c#
(2 answers)
Closed 1 year ago.
I am trying to get the List from a JSON string from a 3rd party API.
I am not able to understand how should I parse it,as the key name starts with numeric.
I do not need the key but I do require value, but I require the value part in my code to be stored in DB.
JSON
{
"5MIN": [
{
"SETTLEMENTDATE": "2021-08-16T00:30:00",
"REGIONID": "NSW1",
"REGION": "NSW1",
"RRP": 39.27,
"TOTALDEMAND": 7416.02,
"PERIODTYPE": "ACTUAL",
"NETINTERCHANGE": -788.69,
"SCHEDULEDGENERATION": 5518.17,
"SEMISCHEDULEDGENERATION": 1076.47
},
{
"SETTLEMENTDATE": "2021-08-16T01:00:00",
"REGIONID": "NSW1",
"REGION": "NSW1",
"RRP": 36.51,
"TOTALDEMAND": 7288.89,
"PERIODTYPE": "ACTUAL",
"NETINTERCHANGE": -828.1,
"SCHEDULEDGENERATION": 5362.3,
"SEMISCHEDULEDGENERATION": 1064.35
}
]
}
I think I am over complicating the issue, but I am confused
As mentioned in the comments above, you can paste the json as code.
Next you add a reference to Newtonsoft.Json:
dotnet add package newtonsoft.json
You then call JsonConvert.Deserialize<T>() as in the example below:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using StackOverflow;
using System.Linq;
//In this example I load the JSON from disk
var json = File.ReadAllText("/home/timothy/data.json");
var record = JsonConvert.DeserializeObject<ServiceResponse>(json);
//No need to convert to List<T> if you're not going to filter it
var results = record.The5Min.ToList();
foreach(var item in results)
{
Console.WriteLine($"{item.Settlementdate}, {item.Regionid}");
}
namespace StackOverflow
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class ServiceResponse
{
[JsonProperty("5MIN")]
public The5Min[] The5Min { get; set; }
}
public partial class The5Min
{
[JsonProperty("SETTLEMENTDATE")]
public DateTimeOffset Settlementdate { get; set; }
[JsonProperty("REGIONID")]
public string Regionid { get; set; }
[JsonProperty("REGION")]
public string Region { get; set; }
[JsonProperty("RRP")]
public double Rrp { get; set; }
[JsonProperty("TOTALDEMAND")]
public double Totaldemand { get; set; }
[JsonProperty("PERIODTYPE")]
public string Periodtype { get; set; }
[JsonProperty("NETINTERCHANGE")]
public double Netinterchange { get; set; }
[JsonProperty("SCHEDULEDGENERATION")]
public double Scheduledgeneration { get; set; }
[JsonProperty("SEMISCHEDULEDGENERATION")]
public double Semischeduledgeneration { get; set; }
}
}
I have a .Json URL that contains Json format data.
HTTPS://XXXX/fetch-transaction?fromdate=2020-10-13&toDate=2020-10-20 (Not working just an example)
[
{
"orderId": 110,
"consignmentNumber": "TEST",
"itemNumbers": [
"TEST"
],
"country": "UK",
"orderType": "ORDER_HOME_DELIVERY",
"paymentTransactionId": "395611",
"priceInOre": 5900,
"paidAt": "2020-10-16 10:51:08",
"orderNumber": "7000067718",
"articleName": "SOUTH-2"
}
]
I would like to insert data into a SQL server table and wonder if it's possible to use SQL server and t-SQL directly here or should I go for VS and C#?
If C# is the preferred choice can someone pleae guide me on how I would accomplish it?
I have created a Console application in Visual studio (however it might be a better solution to use something els then to create a command line applcation?) or guide me in the right direction.
You can try the following code to get the value from the json txt and transfer it to the sql server table.
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("D:\\test1.txt");
List<Example> list = JsonConvert.DeserializeObject<List<Example>>(json);
string strcon = #"Connstr";
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
string sql = "Insert into JsonData(orderId,consignmentNumber,itemNumbers,country,orderType,paymentTransactionId,priceInOre,paidAt,orderNumber,articleName) values(#orderId,#consignmentNumber,#itemNumbers,#country,#orderType,#paymentTransactionId,#priceInOre,#paidAt,#orderNumber,#articleName)";
SqlCommand command = new SqlCommand(sql, connection);
foreach (Example item in list)
{
command.Parameters.AddWithValue("#orderId", item.orderId);
command.Parameters.AddWithValue("#consignmentNumber", item.consignmentNumber);
command.Parameters.AddWithValue("#itemNumbers", item.itemNumbers.First());
command.Parameters.AddWithValue("#country", item.country);
command.Parameters.AddWithValue("#orderType", item.orderType);
command.Parameters.AddWithValue("#paidAt", item.paidAt);
command.Parameters.AddWithValue("#paymentTransactionId", item.paymentTransactionId);
command.Parameters.AddWithValue("#priceInOre", item.priceInOre);
command.Parameters.AddWithValue("#articleName", item.articleName);
command.Parameters.AddWithValue("#orderNumber", item.orderNumber);
}
command.ExecuteNonQuery();
connection.Close();
}
}
public class Example
{
public int orderId { get; set; }
public string consignmentNumber { get; set; }
public List<string> itemNumbers { get; set; }
public string country { get; set; }
public string orderType { get; set; }
public string paymentTransactionId { get; set; }
public int priceInOre { get; set; }
public string paidAt { get; set; }
public string orderNumber { get; set; }
public string articleName { get; set; }
}
Final result:
Edit:
var json = new WebClient().DownloadString("URL");
I've been trying to do this for some time now without good results. My obj.title call seems to return an empty string.
So far I have:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Test2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28");
var obj = JsonConvert.DeserializeObject<MyClass>(json);
label.Content = obj.title;
}
}
}
public class MyClass
{
public string title { get; set; }
}
}
The URL I'm using is https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28
So your JSON source returns an object that looks like this:
{
"status": "ok",
"source": "business-insider",
"sortBy": "top",
"articles": [{
"author": "Allan Smith",
"title": "Ethics experts say Trump's latest move to distance himself from his business empire is not enough: 'Nothing of consequence has changed'",
"description": "Trump says he'll make \"no new deals\" and will pass control of his business empire off to his two adult sons and executives once he assumes office.",
"url": "http://www.businessinsider.com/trump-conflicts-of-interest-latest-move-2016-12",
"urlToImage": "http://static2.businessinsider.com/image/584f0536a1a45e1a008b53ba-1190-625/ethics-experts-say-trumps-latest-move-to-distance-himself-from-his-business-empire-is-not-enough-nothing-of-consequence-has-changed.jpg",
"publishedAt": "2016-12-13T22:55:20Z"
}, {
"author": "Pamela Engel",
"title": "'All anyone ever wanted was to be treated no better than animals': Syrians lose hope as Aleppo falls",
"description": "The Syrian city of Aleppo has mostly fallen to regime forces, leaving many who oppose the brutal rule of President Bashar al-Assad feeling hopeless.",
"url": "http://www.businessinsider.com/aleppo-siege-assad-syria-2016-12",
"urlToImage": "http://static2.businessinsider.com/image/58508de0ca7f0cc2178b4e05-1190-625/all-anyone-ever-wanted-was-to-be-treated-no-better-than-animals-syrians-lose-hope-as-aleppo-falls.jpg",
"publishedAt": "2016-12-13T23:34:31Z"
}] //trimmed due to repetitiveness
}
The JSON object doesn't have a property title. It has an array of articles each of which have a title.
You would need classes that look like:
public class SomeArticles
{
public List<Article> Articles{get;set;}
}
and
public class Article
{
public string Title{get;set;}
}
then you would
var someArticles = JsonConvert.DeserializeObject<SomeArticles>(json);
then
var firstArticleTitle = someArticles.Articles.First().Title;
You can do something like this:
void Main()
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://newsapi.org/v1/articles?source=business-insider&sortBy=top&apiKey=f47672429b7044a29e7a4671f9f41c28");
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.articles[0].title);
}
}
public class Article
{
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public string publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string source { get; set; }
public string sortBy { get; set; }
public List<Article> articles { get; set; }
}
Regards
The class that you deserialize should be
public class MyClass
{
public Article[] articles { get; set; }
}
public class Article
{
public string title { get; set; }
}
From the JSON structure, it looks like the root object doesn't have a title variable. There is an array of articles, each with their own title.
I have 3 class. Those are places.cs, onePlace.cs and placestovisit.cs.
placestovisit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class placestovisit
{
public bool IsDataLoaded { get; set; }
public onePlace sunamganj { get; set; }
public static string basePlaces = "Assets/Places/";
private string baseTanguar = basePlaces + "Tanguar/";
private string baseBaruni = basePlaces + "Baruni/";
public void LoadData()
{
sunamganj = createSunamganj();
IsDataLoaded = true;
}
private onePlace createSunamganj()
{
onePlace data = new onePlace();
data.Items.Add(new places()
{
ID = "0",
Title = "Tanguar Haor",
shortDescription="Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District.",
itemImage = baseTanguar + "1.jpg",
FullDescription = "Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District. The marshes are inter connected with one another through narrow Channels but merge into a single large water body during monsoon. The aquatic vegetation and less disturbance from the human are instrument to invite a large variety of waterfowl specially winter migrant ducks that congregates in thousands. Resident and local migrant, raptor, waders and passerine birds made the area as one of the Asia's most potential birding place. Tanguar Haor is listed as a Ramsar site under the Ramsar Convention in 2000."
});
}
}
onePlace.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class onePlace
{
public string Title { get; set; }
public List<places> Items { get; set; }
public onePlace()
{
Items = new List<places>();
}
}
}
places.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class places
{
public string ID { get; set; }
public string Title { get; set; }
public string shortDescription { get; set; }
public string FullDescription { get; set; }
public string itemImage { get; set; }
public List<string>Gallery { get; set; }
}
}
I want to add item into Gallery from placestovisit class. For that what to do?
Actually I want to add one photo gallery for each object. But I am not so much good in OOP. At this moment can I go with this concept or need to change the concept. If I can go with this one then how can I add item into Gallery from placestovisit class?
Gallery is just a property of your places class, and you can add items by accessing that property via an instance of places class.
One thing you should remember that the properties of reference types are null by default, so you need to initialize them.You can do that in your constructor:
public class places
{
public places()
{
Gallery = new List<string>();
}
}
Then you can add new items to your list like:
var plc = new places() { /* set the properties */ }
plc.Gallery.Add("new gallery");
This is my first try to deserialize a JSON string returned by Facebook.
I want to make sure future developers can maintain my code comfortably so I would like to know if this is okay way to do it. I am concerned that if the JSON string change then I will need to rewrite some of my classes.
Is the JSON string returned from Facebook likely to change? For example if location became a different object I will need to make changes right?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;
//--- If you are not able to add reference dont worry. You probably need to install ASP.NET Ajax or target higher .NET Framework (3.5 or 4).
//--- There are Stack Overflow threads about this.
using System.Web.Script.Serialization;
//--- Our Facebook Person class.
public class FBPerson
{
public string id { get; set; }
public string email { get; set; }
public string name { get; set; }
public string gender { get; set; }
public IDName location { get; set; }
public List<FBObject> work { get; set; }
public List<FBObject> education { get; set; }
}
//-- In some cases only id and name will be accessed
public class IDName
{
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
//-- work and education presently are array of json strings
public class FBObject
{
public IDName employer { get; set; }
public IDName school { get; set; }
}
static class Program
{
//-- Sample JSON string returned by Facebook
const string json2 = #"{
""id"":""11111111111111111"",
""name"":""Tester Test"",
""first_name"":""Tester"",
""last_name"":""Test"",
""link"":""http:\/\/www.facebook.com\/profile.php?id=11111111111111111"",
""location"":
{""id"":""107991659233606"",""name"":""Atlanta, Georgia""},
""work"":
[{""employer"":{""id"":""222222222222222222"",""name"":""Various""}}],
""education"":
[
{""school"":{""id"":""108000000000000"",""name"":""Test High School""},""type"":""High School""},
{""school"":{""id"":""105000000000000"",""name"":""Tester College""},""type"":""College""}
],
""gender"":""male"",
""email"":""tester\u0040gmail.com"",
""timezone"":-5,""locale"":""en_US"",
""verified"":true,
""updated_time"":""2011-11-21T21:10:20+0000""
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
FBPerson fperson = ser.Deserialize<FBPerson>(json2);
//-- Display the user info from the JSON string
Console.WriteLine(fperson.id.ToString());
Console.WriteLine(fperson.name.ToString());
Console.WriteLine(fperson.gender.ToString());
Console.WriteLine(fperson.email.ToString());
Console.WriteLine(fperson.location.name.ToString());
Console.WriteLine(fperson.work[0].employer.name.ToString());
Console.WriteLine(fperson.education[0].school.name.ToString());
Console.ReadLine();
}
}
This seems fine. No matter how you do deserialization, changes to the JSON data format would break you. For that reason, API authors try very hard to avoid making such changes.
I don't know whether you are open to other approaches but in case you may want to try,
here is an alternative way that doesn't need FBPerson IDName FBObject classes and makes use of Json.Net and this extension methods
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
static class Program
{
//-- Sample JSON string returned by Facebook
const string json2 = #"{
""id"":""11111111111111111"",
""name"":""Tester Test"",
""first_name"":""Tester"",
""last_name"":""Test"",
""link"":""http:\/\/www.facebook.com\/profile.php?id=11111111111111111"",
""location"":
{""id"":""107991659233606"",""name"":""Atlanta, Georgia""},
""work"":
[{""employer"":{""id"":""222222222222222222"",""name"":""Various""}}],
""education"":
[
{""school"":{""id"":""108000000000000"",""name"":""Test High School""},""type"":""High School""},
{""school"":{""id"":""105000000000000"",""name"":""Tester College""},""type"":""College""}
],
""gender"":""male"",
""email"":""tester\u0040gmail.com"",
""timezone"":-5,""locale"":""en_US"",
""verified"":true,
""updated_time"":""2011-11-21T21:10:20+0000""
}";
public static void Main()
{
dynamic fperson = JsonUtils.JsonObject.GetDynamicJsonObject(json2);
//-- Display the user info from the JSON string
Console.WriteLine(fperson.id.ToString());
Console.WriteLine(fperson.name.ToString());
Console.WriteLine(fperson.gender.ToString());
Console.WriteLine(fperson.email.ToString());
Console.WriteLine(fperson.location.name.ToString());
Console.WriteLine(fperson.work[0].employer.name.ToString());
Console.WriteLine(fperson.education[0].school.name.ToString());
Console.ReadLine();
}
}