How can you decrypt/ deserialize dataset. here is what i am getting from the web service. I am new to xamarin forms. Thanks in advance. i tried this json2csharp.com to convert, but got an error because it can convert datatable to csharp but not datasets.
[
[
{
"bit_HasError":false,
"vchar_ErrorMsg":""
}
],
[
{
"int_SurveyQuestionID":1,
"vchar_Description":"we",
"vchar_Instruction":"Question Instruction",
"int_AnswerType":1
},
{
"int_SurveyQuestionID":5,
"vchar_Description":"this is the question 2",
"vchar_Instruction":null,
"int_AnswerType":2
}
],
[
{
"int_SurveyQuestionID":1,
"vchar_Option":"option1"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer1"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer2"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer3"
},
{
"int_SurveyQuestionID":1,
"vchar_Option":"optionn2"
}
]
]
Using https://app.quicktype.io/ it is quite easy to get started, just copy paste your json in there, here is the result:
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var prject = Prject.FromJson(jsonString);
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Prject
{
[JsonProperty("bit_HasError", NullValueHandling = NullValueHandling.Ignore)]
public bool? BitHasError { get; set; }
[JsonProperty("vchar_ErrorMsg", NullValueHandling = NullValueHandling.Ignore)]
public string VcharErrorMsg { get; set; }
[JsonProperty("int_SurveyQuestionID", NullValueHandling = NullValueHandling.Ignore)]
public long? IntSurveyQuestionId { get; set; }
[JsonProperty("vchar_Description", NullValueHandling = NullValueHandling.Ignore)]
public string VcharDescription { get; set; }
[JsonProperty("vchar_Instruction")]
public string VcharInstruction { get; set; }
[JsonProperty("int_AnswerType", NullValueHandling = NullValueHandling.Ignore)]
public long? IntAnswerType { get; set; }
[JsonProperty("vchar_Option", NullValueHandling = NullValueHandling.Ignore)]
public string VcharOption { get; set; }
}
public partial class Prject
{
public static List<List<Prject>> FromJson(string json) => JsonConvert.DeserializeObject<List<List<Prject>>>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this List<List<Prject>> self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
P.S.: Please note that you have to modify the class names.
Related
I'm trying to read from appsetings.json file some data just like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
//sercies.Configure<Models.AppDate>(Configuration);
services.Configure<Models.AppData>(Configuration.GetSection("AppData"));
//It does not works
string option = Configuration.Get<Models.AppData>().AnotherOption;
//It works
string anotherOption = Configuration["AppData:AnotherOption"];
// Add framework services.
services.AddMvc();
}
With these classes:
public class AppData
{
public Jwt Jwt { get; set; }
public string AnotherOption { get; set; }
}
public class Jwt
{
public string Audience { get; set; }
public string Issuer { get; set; }
}
And in appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AppData": {
"Jwt": {
"Audience": "http://localhost:5000",
"Issuer": "http://localhost:5000"
},
"AnotherOption": "Not yet"
}
}
When i debug, option var it's null. ¿How can i implement this?. Ty
I am not really sure why the code above doesn't work.
But I know other ways to do it.
string option = Configuration.GetSection("AppData").Get<Models.AppData>().AnotherOption;
or
string option = ConfigurationBinder.Get<Models.AppData>(Configuration.GetSection("AppData")).AnotherOption;
public IConfiguration Configuration { get; }
Below method can access the data from appsettings.json
public void ConfigureServices(IServiceCollection services)
{
var config = Configuration.GetSection("Application").Get<Application>();
}
//Model class
public class Application
{
public string ServiceUrl { get; set; }
}
I am new to asp.net MVC. I hav to return Json from controller to view using ajax call, that is perfect.
I want to return below json format to view.
[{
"name": "A",
"data": [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] },
{
"name": "B",
"data": [3.9, 2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
},
{
"name": "C",
"data": [3.9, 2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
I have tried below modal to return such a format,
public class myModel
{
public List<string> Name { get; set; }
public List<float> Average { get; set; }
}
What should be my model like to return above mentioned format?
MyModel should be modified like this
public class MyModel
{
public string name { get; set; }
public List<float> data { get; set; }
}
as name property is only for a single string, and data is actually the array holding the float values.
You can return List<MyModel> or array - MyModel[] as JSON from ajax call
model type should be:
public class myModel
{
public string name { get; set; }
public List<float> data { get; set; }
}
AND in Controller:
List<myModel> list=new List<myModel>();
return new JsonResult()
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = Int32.MaxValue
};
public class MyModel
{
public string Name { get; set; }
public List<float> Data { get; set; }
}
public JsonResult MyMethod()
{
List<MyModel> list = new List<MyModel>();
// Do stuff
return Json(list);
}
Viewmodel:
public class ViewModel
{
public List<MyModel> myModel {get;set;}
}
myModel should be like this:
public class myModel
{
public string name { get; set; }
public IList<double> data { get; set; }
}
You can easily generate this kind of task with jsonutils online.
Your model should be like this.
public class myModel
{
public string name { get; set; }
public List<double> data { get; set; }
}
Here name contain single string value and data is contain array of double value.
Note : Use json2charp to convert your JSON to c# class type or if you are using vs2013 or above version paste copied JSON in C# class type.
I am using ASP.NET 5 and I want to use POCO classes to access my appsettings.json file. This file looks like this:
{
"Data": {
"ErpSystemConnection": {
"ConnectionString": "[myConnectionString]"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Verbose",
"System": "Information",
"Microsoft": "Information"
}
},
"GoogleAnalytics": {
"Account": [
{
"Name": "AccountName",
"ServiceAccountEmailAddress": "someEmail#someaccount.iam.gserviceaccount.com",
"KeyFileName": "key1.p12",
"Password": "notasecret"
},
{
"Name": "AnotherAccount",
"ServiceAccountEmailAddress": "anotherEmailAccount#someotheraccount.iam.gserviceaccount.com",
"KeyFileName": "key2.p12",
"Password": "notasecret"
}
],
"KeyFilePath": "/googleApis/"
}
}
The 'GoogleAnalytics' key contains an array of accounts that I wish to be able to access in a collection either as a list or an array.
I created a POCO to represent this key that contains a corresponding collection of 'Account' objects:
public class GoogleAnalytics
{
public Account[] Account { get; set; } = new Account[1];
public string KeyFilePath { get; set; }
public GoogleAnalytics()
{
}
}
And the 'Account' object:
public class Account
{
private const string _applicationName = #"Storefront Analytics";
private X509Certificate2 _certificate;
private ServiceAccountCredential _credential;
private AnalyticsService _service;
#region |--Properties--|
public string Name { get; set; }
public string Password { get; set; }
public string ServiceAccountEmailAddress { get; set; }
public string KeyFileName { get; set; }
public string KeyFilePath { get; set; }
public string KeyFileFullPath
{
get
{
return $"{KeyFilePath}{KeyFileName}";
}
}
public X509Certificate2 Certificate
{
get
{
if(_certificate == null)
{
ConfigureInstance();
}
return _certificate;
}
set
{
_certificate = value;
}
}
public ServiceAccountCredential Credential
{
get
{
if (_credential == null)
{
ConfigureInstance();
}
return _credential;
}
set
{
_credential = value;
}
}
public AnalyticsService Service
{
get
{
if (_service == null)
{
ConfigureInstance();
}
return _service;
}
set
{
_service = value;
}
}
#endregion
#region |--Constructors--|
public Account()
{
}
public Account(string password, string keyFileName,
string keyFilePath,
string serviceAccountEmailAddress, string accountName)
{
//TODO: Validate parameters
Password = password;
KeyFileName = keyFileName;
KeyFilePath = keyFilePath;
ServiceAccountEmailAddress = serviceAccountEmailAddress;
Name = accountName;
}
#endregion
private void ConfigureInstance()
{
Certificate = new X509Certificate2(KeyFileFullPath, Password, X509KeyStorageFlags.Exportable);
Credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(ServiceAccountEmailAddress)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
});
Service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = _applicationName
});
}
}
My Controller:
public class GoogleAnalyticsController : Controller
{
#region |--Properties--|
[FromServices]
private IGoogleAnalyticsRepository _repo { get; set; }
#endregion
public GoogleAnalyticsController(IOptions<GoogleAnalytics> options)
{
var temp = options.Value;
}
}
The 'KeyFilePath' property is properly set in the IOptions instance.
The problem I am having is that the Account array contains null references - none of the accounts are being instantiated. I wondering if I am doing this wrong, or the Options Model doesn't support this type of behavior at this time?
Update in response to Shaun Luttin's answer
I implemented the changes listing in Shaun Luttin's answer. There seems to have been an additional problem. For whatever reason, all of the Account instances' properties were null until I simplified the class as follows:
public class Account
{
public string Name { get; set; }
public string Password { get; set; }
public string ServiceAccountEmailAddress { get; set; }
public string KeyFileName { get; set; }
public string KeyFilePath { get; set; }
}
Short Answer
I wondering if I am doing this wrong, or the Options Model doesn't support this type of behavior at this time?
You are doing one thing wrong. The Options Model does support arrays. You need NOT to initialize your array property with an array of size [1].
public Account[] Account { get; set; } = new Account[1]; // wrong
public Account[] Account { get; set; } // right
Demo
Here is a sample, just for you, that you can find here on GitHub.
MyOptions.cs
namespace OptionsExample
{
public class MyObj
{
public string Name { get; set; }
}
public class MyOptions
{
public string Option1 { get; set; }
public string[] Option2 { get; set; }
public MyObj[] MyObj { get; set; }
}
}
Startup.cs
namespace OptionsExample
{
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.OptionsModel;
using System.Linq;
public class Startup
{
public IConfigurationRoot Config { get; set; }
public Startup(IHostingEnvironment env)
{
Config = new ConfigurationBuilder().AddJsonFile("myoptions.json").Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<MyOptions>(Config);
}
public void Configure(IApplicationBuilder app,
IOptions<MyOptions> opts)
{
app.Run(async (context) =>
{
var message = string.Join(",", opts.Value.MyObj.Select(a => a.Name));
await context.Response.WriteAsync(message);
});
}
}
}
myoptions.json
{
"option1": "option1val",
"option2": [
"option2val1",
"option2val2",
"option2val3"
],
"MyObj": [
{
"Name": "MyObj1"
},
{
"Name": "MyObj2"
}
]
}
project.json dependencies
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
}
Output
I've been tasked will calling an API, that needs to take a JSON payload as its request.. An example format of the JSON is as follows:
{
"method":"methodname",
"in":[
{
"account":"acme",
"context":"abc123"
},
"content",
{
"mSearchText":"chocolate",
"mItemDataIDs":[
"Entry:ID",
"Entry:EntryRef",
"Entry:CategoryID"
]
}
]
}
I am using JSON.NET (Newstonsoft) to construct my JSON from .net objects.
The issue I am facing is correctly constructing the "in" section..
It appears to be an array of objects, but only the second item has a title ("content",{.....})..
The closest I can get is:
{
"method": "methodname",
"in":[
{
"account": "PANDO",
"context": "sdfsd22342"
},
{
"mSearchText":"chocolate",
"mItemDataIDs":[
"Entry:ID",
"Entry:EntryRef",
"Entry:CategoryID"
]
}
]
}
Which is identical apart from "content", is missing:
My code so far is:
public class Payload
{
public string method { get; set; }
[JsonProperty("in")]
public List<object> Items { get; set; }
}
public class AccountDetails
{
public string account { get; set; }
public string context { get; set; }
}
[JsonObject(Title = "content")]
public class Content
{
public string mSearchText { get; set; }
public string[] mItemDataIDs { get; set; }
}
Payload payload = new Payload();
payload.method = "methodname";
payload.Items = new List<object>();
payload.Items.Add(new AccountDetails
{
account = "acme",
context = "abc123"
});
Content conent = new Content
{
mSearchText = "chocolate",
mItemDataIDs = new string[] { "Entry:ID", "Entry:EntryRef", "Entry:CategoryID" }
};
payload.Items.Add(conent);
string jsonObject = JsonConvert.SerializeObject(payload, Formatting.Indented);
Any suggestions on what I can do?
My Json is of the following format.
{
"code" : o,
"message" : "success",
"book_list":
[
{"name": "C","price":180},
{"name": "C++","price":180},
{"name": "C#","price":180},
]
}
I am a brand new beginner to Windows phone app development!!
How shall i get list of books from the url and store it in a dictionary kind of thing??(i.e as a key value pair) for windows phone 7??
You can use this JSON framework for .NET:
using System.Runtime.Serialization;
[DataContract]
public class BookShop
{
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "book_list")]
public List<Book> Result { get; set; }
}
[DataContract]
public class Book
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "price")]
public int Price { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
string json = "{\"code\": 0,\"message\": \"success\",\"book_list\": [{\"name\": \"C\",\"price\": 180}, {\"name\": \"C++\",\"price\": 180 }, {\"name\": \"C#\",\"price\": 180}]}";
var myObjects = JsonConvert.DeserializeObject<BookShop>(json);
foreach (var item in myObjects.Result)
{
Debug.WriteLine("{0} has price {1}", item.Name, item.Price);
}
}
}