c# json newtonsoft conversion - c#

Im trying to create a serialize string from this json:
report_details = {
'reportTypeLang' : 'conversations',
'reportDirections' : {
'selected' : 'inbound'
},
'times' : {
'dateRange' : 'Last5Minutes'
},
'filters' : {
'sdfDips_0' : 'in_AC10033A_AC10033A-410'
},
'dataGranularity' : {
'selected' : 'auto'
}
so far i have created these classes:
public class ReportDetails
{
public string reportTypeLang { get; set; }
public ReportDirections reportDirections { get; set; }
public Times times { get; set; }
public Filters filters { get; set; }
public DataGranularity dataGranularity { get; set; }
}
public class ReportDirections
{
public string selected { get; set; }
}
public class Times
{
public string dateRange { get; set; }
}
public class Filters
{
public string sdfDips_0 { get; set; }
}
public class DataGranularity
{
public string selected { get; set; }
}
and tried to use this code to build the data:
ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";
ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";
Times Times = new Times();
Times.dateRange = "Last5Minutes";
Filters Filters = new Filters();
Filters.sdfDips_0 = "in_AC10033A_AC10033A-410";
DataGranularity DataGranularity = new DataGranularity();
DataGranularity.selected = "auto";
string report_details = JsonConvert.SerializeObject(ReportDetails);
but this only seems to result in this object:
"{\"reportTypeLang\":\"conversations\",\"reportDirections\":null,\"times\":null,\"filters\":null,\"dataGranularity\":null}"
How do i popluate all the sections as per the original json?

You did not assign the other properties. Therfore their serialized values remain null.
Just add them, like you assigned a reportTypeLang:
ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";
ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";
ReportDetails.reportDirections = reportDirections; // and so with the other props
And as a side-note: there's a cool feature paste JSON as classes which autogenerates the neccessary classes for you, if you don't wanna write them down yourself:

Related

how to get data from json in c#?

I Get json data from third party in json format.
I am trying to fetch RollId from "Id" and MType from "Data" in some cases
"Data" doesn't have fields it is kind of blank.
It's working when we have "Data". In case of blank it's not working.
any idea on this? Is there a better approach of doing this?
This is the Json
string json = #"{
'root': {
'_type': '_container',
'Class': '.key.PModel',
'Elements': {
'_type': 'array<element>',
'_data': [
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'testId',
'Class': '.key.PModel',
'RollId': '.key.7157'
},
'Data': {
'_type': 'p_model',
'Class': '.key.Unsupported',
'MType': '.TestMType',
'Version': {
'_type': 'test__version',
'Class': '.key.TestVersion',
}
}
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.11261'
},
'Data': '.ref.root.Elements.0.Data'
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.7914'
},
'Data': '.ref.root.Elements.0.Data'
}
]
}
}
}";
This is the Code
public class Program
{
static void Main(string[] args)
{
//it provide json
var testCont = thirdpartyapi();
var dataList = new List<TestResponse>();
foreach (var testData in testCont.Elements())
{
var data = new TestResponse();
data.col1 = Convert.ToInt32(testData.Id().RollId());
data.col2 = testData.Data().MType().ToString();
dataList.Add(data);
}
}
public class TestResponse
{
public int col1 { get; set; }
public string col2 { get; set; }
}
}
First, try to get a valid well-formed json. You can use this code beautify tool. Then you can automatically generate C# class using json2csharp. Finally as you have C# class you can apply if statements and check if property is null.
Generated C# wrapper:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
If you want to pick only few fields from complex JSON, you can consider using Cinchoo ETL - an open source library
Sample below shows how to pick RollId and MType values from your json
using (var r = new ChoJSONReader("## YOUR JSON FILE PATH ##")
.WithJSONPath("$.._data")
.WithField("RollId", jsonPath: "$..Id.RollId", fieldType: typeof(string))
.WithField("MType", jsonPath: "$..Data.MType", fieldType: typeof(string))
)
{
foreach (var rec in r)
{
Console.WriteLine((string)rec.RollId);
Console.WriteLine((string)rec.MType);
}
}
Hope it helps.
The easiest way is use the DataContractJsonSerializer
Here you can read more about it.
All in all you need to create a model which has the same possible outcome as your json.
Then you can just use the DataContractJsonSerializer to create an object of you model by using a MemoryStream.
Here you can find a nice tool to create the model from the JSON.
For example this one:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
Then you use the MemoryStream and the DataContractJsonSerializer to Create an object of RootObject from that JSON.
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
stream1.Position = 0;
RootObject rootObject = (RootObject)ser.ReadObject(stream1);
And yes, as Adriani6 mentiones - your JSON is invalid at this point:
"Data": {
"_type": "p_model",
"Class": ".key.Unsupported",
"MType": ".TestMType",
"Version": {
"_type": "test__version",
"Class": ".key.TestVersion",
}
There is a , at the end wich is not allowed.

Read and parse Json on c# and get specific values

I'm trying to parse a Json that contains a lot of objects.
.json look like this:
:
{
"status" : "success",
"prices" : [
{
"market_hash_name" : "4X4 Car",
"price" : "7.87",
"created_at" : 1472587613
},
{
"market_hash_name" : "Yellow Car",
"price" : "27.75",
"created_at" : 1472519899
}
[...] etc
and I just want to get the price of specific market hash name. How can I do that?
I have got this atm
using System.IO;
using Newtonsoft.Json;
public class MarketHandler
{
//Methods
public MarketHandler updatePrices()
{
var json = File.ReadAllText("PriceSkins.json");
currentPrices = JsonConvert.DeserializeObject<Data>(json);
return this;
}
public Data currentPrices { get; set; }
public class Data
{
public Response response { get; set; }
}
public class Response
{
public string status { get; set; }
public Price prices { get; set; }
}
public class Price
{
public string market_hash_name { get; set; }
public string price { get; set; }
public int created_at { get; set; }
}
You can do like this, place your JSON some where else on your system and load the JSON like below
Rootobject ro = new Rootobject();
StreamReader sr = new StreamReader(Server.MapPath("text.json"));
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<Rootobject>(jsonString);
Before that you have to create the classes like below these classes are matching your JSON, already I have answer similar this question here you can cehck how to create classes for JSON easily
public class Rootobject
{
public string status { get; set; }
public Price[] prices { get; set; }
}
public class Price
{
public string market_hash_name { get; set; }
public string price { get; set; }
public int created_at { get; set; }
}
After that,from the instance of the Rootobject(ro) you can access the price like below
Price[] price_list = ro.prices;

How to populate list as class object?

How do you populate a list as a class object? For example, this does not work:
[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}
public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}
public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
This is controller action:
public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();
List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;
return jsonReviewFormFields;
}
The code crashes at
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
It's probably a basic object orientated error. How do you populate the list?
You are not instantiating it, you have to instantiated the type first:
jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();
and then set property of it:
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort
before that you also have to instantiate main class which i don't see in your controller action anywhere :
JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();

c# POST json not working as expected?

I have this example python script that im trying to convert to c# using newtonsoft :
import urllib
import urllib2
import json
url = 'http://server.net/fcgi/scrut_fcgi.fcgi'
report_details = {
'reportTypeLang' : 'conversations',
'reportDirections' : {
'selected' : 'inbound'
},
'times' : {
'dateRange' : 'Last5Minutes'
},
'filters' : {
'sdfDips_0' : 'in_AC10033A_AC10033A-410'
},
'dataGranularity' : {
'selected' : 'auto'
}
}
data_i_need = {
'inbound' : {
'table' : {
'query_limit' : {
'offset' : 0,
'max_num_rows' : 1
}
}
},
'outbound' : {
'table' : {
'query_limit' : {
'offset' : 0,
'max_num_rows' : 1
}
}
}
}
data = {
'rm' : 'report_api',
'action' : 'get',
'rpt_json' : json.dumps( report_details ),
'data_requested' : json.dumps( data_i_need )
}
data = urllib.urlencode( data )
req = urllib2.Request( url, data )
response = urllib2.urlopen( req )
report = response.read()
report_obj = json.loads( report )
so far with some help i have the following c# code but it does not return any data like the python version just errors as if the request is incorrect:
class Program
{
static void Main(string[] args)
{
ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";
Times Times = new Times();
Times.dateRange = "Last5Minutes";
Filters Filters = new Filters();
Filters.sdfDips_0 = "in_AC10033A_AC10033A-410";
DataGranularity DataGranularity = new DataGranularity();
DataGranularity.selected = "auto";
ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";
ReportDetails.reportDirections = reportDirections;
ReportDetails.times = Times;
ReportDetails.filters = Filters;
ReportDetails.dataGranularity = DataGranularity;
//
QueryLimit QueryLimit = new QueryLimit();
QueryLimit.offset = 0;
QueryLimit.max_num_rows = 1;
QueryLimit2 QueryLimit2 = new QueryLimit2();
QueryLimit2.offset = 0;
QueryLimit2.max_num_rows = 1;
Table Table = new Table();
Table.query_limit = QueryLimit;
Table2 Table2 = new Table2();
Table2.query_limit = QueryLimit2;
Inbound Inbound = new Inbound();
Inbound.table = Table;
Outbound Outbound = new Outbound();
Outbound.table = Table2;
DataINeed DataINeed = new DataINeed();
DataINeed.inbound = Inbound;
DataINeed.outbound = Outbound;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://server.bobo.net/fcgi/scrut_fcgi.fcgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new
{
action = "get",
rm = "report_api",
data_requested = DataINeed,
rpt_json = ReportDetails
});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
public class tw
{
public string rm { get; set; }
public string action { get; set; }
public string rpt_json { get; set; }
public string data_requested { get; set; }
}
public class DataINeed
{
public Inbound inbound { get; set; }
public Outbound outbound { get; set; }
}
public class Inbound
{
public Table table { get; set; }
}
public class Outbound
{
public Table2 table { get; set; }
}
public class Table
{
public QueryLimit query_limit { get; set; }
}
public class Table2
{
public QueryLimit2 query_limit { get; set; }
}
public class QueryLimit
{
public int offset { get; set; }
public int max_num_rows { get; set; }
}
public class QueryLimit2
{
public int offset { get; set; }
public int max_num_rows { get; set; }
}
public class ReportDetails
{
public string reportTypeLang { get; set; }
public ReportDirections reportDirections { get; set; }
public Times times { get; set; }
public Filters filters { get; set; }
public DataGranularity dataGranularity { get; set; }
}
public class ReportDirections
{
public string selected { get; set; }
}
public class Times
{
public string dateRange { get; set; }
}
public class Filters
{
public string sdfDips_0 { get; set; }
}
public class DataGranularity
{
public string selected { get; set; }
}
public class bob
{
}
does this look like the correct way to POST the json request or does something look wrong?
Thanks
Try this..
using System.Net;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
ReportDirections reportDirections = new ReportDirections();
reportDirections.selected = "inbound";
Times Times = new Times();
Times.dateRange = "Last5Minutes";
Filters Filters = new Filters();
Filters.sdfDips_0 = "in_AC10033A_AC10033A-410";
DataGranularity DataGranularity = new DataGranularity();
DataGranularity.selected = "auto";
ReportDetails ReportDetails = new ReportDetails();
ReportDetails.reportTypeLang = "conversations";
ReportDetails.reportDirections = reportDirections;
ReportDetails.times = Times;
ReportDetails.filters = Filters;
ReportDetails.dataGranularity = DataGranularity;
//
QueryLimit QueryLimit = new QueryLimit();
QueryLimit.offset = 0;
QueryLimit.max_num_rows = 1;
QueryLimit2 QueryLimit2 = new QueryLimit2();
QueryLimit2.offset = 0;
QueryLimit2.max_num_rows = 1;
Table Table = new Table();
Table.query_limit = QueryLimit;
Table2 Table2 = new Table2();
Table2.query_limit = QueryLimit2;
Inbound Inbound = new Inbound();
Inbound.table = Table;
Outbound Outbound = new Outbound();
Outbound.table = Table2;
DataINeed DataINeed = new DataINeed();
DataINeed.inbound = Inbound;
DataINeed.outbound = Outbound;
WebClient _webClient = new WebClient();
_webClient.Headers.Add("Content-Type", "application/json");
string data_requested = HttpUtility.UrlEncode(JsonConvert.SerializeObject(DataINeed));
string rpt_json = HttpUtility.UrlEncode(JsonConvert.SerializeObject(ReportDetails));
string data = "action=get&rm=report_api&data_requested=" + data_requested + "&rpt_json="+rpt_json;
string address = "http://server/fcgi/scrut_fcgi.fcgi";
var responseText = Encoding.Default.GetString(_webClient.UploadData(address, "POST", Encoding.Default.GetBytes(data)));
Console.WriteLine(responseText);
}
}
public class tw
{
public string rm { get; set; }
public string action { get; set; }
public string rpt_json { get; set; }
public string data_requested { get; set; }
}
public class DataINeed
{
public Inbound inbound { get; set; }
public Outbound outbound { get; set; }
}
public class Inbound
{
public Table table { get; set; }
}
public class Outbound
{
public Table2 table { get; set; }
}
public class Table
{
public QueryLimit query_limit { get; set; }
}
public class Table2
{
public QueryLimit2 query_limit { get; set; }
}
public class QueryLimit
{
public int offset { get; set; }
public int max_num_rows { get; set; }
}
public class QueryLimit2
{
public int offset { get; set; }
public int max_num_rows { get; set; }
}
public class ReportDetails
{
public string reportTypeLang { get; set; }
public ReportDirections reportDirections { get; set; }
public Times times { get; set; }
public Filters filters { get; set; }
public DataGranularity dataGranularity { get; set; }
}
public class ReportDirections
{
public string selected { get; set; }
}
public class Times
{
public string dateRange { get; set; }
}
public class Filters
{
public string sdfDips_0 { get; set; }
}
public class DataGranularity
{
public string selected { get; set; }
}
public class bob
{
}
managed to get it working by changing the content-type to :
_webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
i was debugging with charles and the python version was posting a json formated form, changed the c# content type to match and now works a treat
Many Thanks for your code and help.

Structure of Json in C#

My Goal:
Read JSON from site, get values of certain items and display them, after I successfully
pull that off I will want to implement taking in a value like true and set it to false.
For starters I need help figuring out how to read and write the variables. I have read
lots of tutorials and blogs about how to read in the data and parse it but what isn't
explained is where is the value stored?
Like I have this http://elsite.com/.json and it has this:
{
dola: "p9", data:{
house: [{
dola: "p9", data:{
owner: "blah", // string
price: blah, // int
url: "http://www.link.com", // url/string
message: "blahblah",
checked: false
}
},
{
dola: "p9", data:{
owner: "blah", // same as above
I have built this to get the data:
[DataContract]
class container
{
[DataMember(Name = "data")]
public Data1 dataStart { get; set; }
[DataContract]
public class Data1
{
[DataMember(Name = "house")]
public HouseA[] home { get; set; }
[DataContract]
public class HouseA
{
[DataMember(Name = "data")]
public Data2 dataSec { get; set; }
[DataContract]
public class Data2
{
[DataMember(Name = "owner")]
public string own { get; set }
[DataMember(Name = "message")]
public strinng mess { get; set; }
}
}
}
}
I want to use
var blah = from post in container.dataStart.house.data // obviously not the right way to do it
select new MessageItem
{
User = post.own,
Meza = post.mess
}
with
public class MessageItem
{
public string User;
public string Meza;
}
So basically it boils down to I am not COMPLETELY understanding the structure of the arrays and objects.
Anyone able to guide me in the right way to do the from.in.select?
Have you looked at Json.NET http://json.codeplex.com/ which includes LINQ to JSON support
I prefer JavaScriptSerializer (System.Web.Extensions.dll) for this; the following works:
JsonResult obj = new JavaScriptSerializer().Deserialize<JsonResult>(json);
var qry = from house in obj.data.house
let post = house.data
select new MessageItem
{
User = post.owner,
Meza = post.message
};
with:
class JsonResult
{
public string dola { get; set; }
public Data data { get; set; }
public class Data
{
public List<House> house { get; set; }
}
public class House
{
public string dola { get; set; }
public HouseData data { get; set; }
}
public class HouseData
{
public string owner { get; set; }
public int price {get;set;}
public Uri url {get;set;}
public string message {get;set;}
public bool #checked {get;set;}
}
}

Categories

Resources