Returns Json format data to me from an api.
However, the type of the "FuelType" property inside the object may be different. For example, 1 time comes as follows:
{
...
fuelType: "gasoline"
...
}}
But then it can happen:
{
...
fuelType: ["gasoline", "any"]
...
}}
If I set the "FuelType" property type on my model to a string, in the second case, Json will give me an error when it arrives, because it can't convert from array to string. No, if I set the type to an array, then, conversely, if a string arrives, it will issue an error because it cannot convert from a string to an array.
In this case, what should I put the "FuelType" property type in my model so that it does not make an error when deserializing?
It all depends on you,what type of value you want to receive?string or List?
I tried with the codes:
public class SomeModel
{
public SomeModel()
{
fuelType = new List<string>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<string> fuelType { get; set; }
//you could move the codes to someservice
public List<string> someresult(string a)
{
var targetlist = new List<string>();
targetlist.Add(a);
return targetlist;
}
public List<string> someresult(List<string> a)
{
var targetlist = new List<string>();
targetlist.AddRange(a);
return targetlist;
}
}
[HttpPost]
public JsonResult SomeAction()
{
var somemodel = new SomeModel() { Id = 1, Name = "name" };
var somevalue = /*"a"*/new List<string>() { "a", "b", "c" };
var targetvalue = somemodel.someresult(somevalue);
somemodel.fuelType.AddRange(targetvalue);
return new JsonResult(somemodel);
}
Result:
try this
var fuelType = JsonConvert.DeserializeObject<MyClass>(json);
public class MyClass
{
[JsonProperty("fuelType")]
private JToken _fuelType;
[JsonIgnore]
public string[] fuelType
{
get {
if (_fuelType==null) return null;
return _fuelType is JArray ? _fuelType.ToObject<string[]>() : new string[] { (string)_fuelType }; }
set { _fuelType = JsonConvert.SerializeObject(value); }
}
}
How to return 2 objects through Json ?
I am building a tag input field from Telerik and I want to pass string values from 2 tables namely, "Skills" and "Expertises" to a tag jquery control.
public JsonResult Skills_Read(string text)
{
var result = GetSkills();
var result1 = GetExpertises();
if (!string.IsNullOrEmpty(text))
{
result = result.Where(p => p.Name.Contains(text)).ToList();
result1 = result1.Where(p => p.Name.Contains(text)).ToList();
}
return Json(result);
}
private IEnumerable<Skill> GetSkills()
{
var result = _context.Skills;
return result;
}
private IEnumerable<Expertise> GetExpertises()
{
var result = _context.Expertises;
return result;
}
You can create a new object.
public JsonResult Skills_Read(string text)
{
var result = GetSkills();
var result1 = GetExpertises();
if (!string.IsNullOrEmpty(text))
{
result = result.Where(p => p.Name.Contains(text)).ToList();
result1 = result1.Where(p => p.Name.Contains(text)).ToList();
}
return Json(new { result, result1 });
}
Also
return Json(new { Skills = result, Expertises = result1 })
Update Working Code I Just span up
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
class One
{
public string Word { get; set; }
}
class Two
{
public string Word { get; set; }
}
// GET api/values
[HttpGet]
public JsonResult Get()
{
return new JsonResult(new {
First = new One { Word = "Some Word" },
Second = new Two { Word = "Another Word" }
});
}
}
Here's what it looks like:
Hi I have a Login API which I am using to login though my xamarin.forms app.
I will post my username and password and in return I am getting some data.Now Iam facing some issues at deserialization of json. Iam getting data at my resultJson but I cant deserialize it. Help me.
My Json :
[
{
"Result":true,
"ID":"fc938df0",
"LoginName":"test",
"UserName":"test",
"ConnectionString":"MSSQLSERVER;Initial Catalog=Test1;User ID=db;Password=db#2018",
"UserProfileID":"fc938df0"
}
]
My API Call class which have deserialization of Json.
public T APICallResult<T>()
{
try
{
Device.BeginInvokeOnMainThread(() =>
{
if (loadingIndicator != null)
{
loadingIndicator.IsRunning = true;
loadingIndicator.IsVisible = true;
}
});
var client = new HttpClient { BaseAddress = baseAddress };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var req = new HttpRequestMessage(HttpMethod.Post, apiurl);
req.Content = new StringContent(postdata, Encoding.UTF8, "application/json");
string stringObtained = "";
Task<string> task = Task.Run(async () => await Threading(client, req));
task.Wait();
stringObtained = task.Result;
var jsonObtained = Regex.Unescape(stringObtained);
int startIndex = jsonObtained.IndexOf('[');
int endIndex = jsonObtained.LastIndexOf(']');
int length = endIndex - startIndex + 1;
var resultJSON = jsonObtained.Substring(startIndex, length);
T resultObject;//Generic type object
try
{
//**Deserializing**
resultObject = JsonConvert.DeserializeObject<T>(resultJSON);//, settings);
removeLoadingAnimation();
return resultObject;
}
catch (Exception e)
{
List<ErrorMessageData> errorMessages = JsonConvert.DeserializeObject<List<ErrorMessageData>>(resultJSON);
errorMessage = errorMessages[0];
removeLoadingAnimation();
return default(T);
}
}
catch (Exception e)
{
errorMessage = new ErrorMessageData();
errorMessage.Flag = false;
errorMessage.Message = e.Message;
removeLoadingAnimation();
return default(T);
}
}
My API call at login class
string postdataForLogin = "{\"userName\":\"" + userName.Text + "\",\"password\":\"" + password.Text + "\",\"RequestURL\":\"" + CommonValues.RequestURL + "\"}";
APICall callForLogin = new APICall("/API/LoginMobile/HomeLogin", postdataForLogin, loadingIndicator);
try
{
List<LoginData> resultObjForLogin = callForLogin.APICallResult <List<LoginData>>();
if (resultObjForLogin != null)
{
LoginData loginData = new LoginData();
loginData = resultObjForLogin[0];
Settings.userID = loginData.UserProfileID;
Settings.connectionString = loginData.ConnectionString;
if (loginData.Result)
{
Device.BeginInvokeOnMainThread(async () =>
{
Navigation.InsertPageBefore(new MainPage(), this);
await Navigation.PopAsync();
});
}
My DataModel
public class LoginData
{
public bool Result { get; set; }
public string ID { get; set; }
public string UserProfileID { get; set; }
public string LoginName { get; set; }
public string UserName { get; set; }
public string ConnectionString { get; set; }
}
Its seems strange, My problem solved after downgrading my xamarin.forms from latest version to pre release 4.0.0.169046- pre5. I think its a xamarin forms bug
I have a class:
public class StatististikaByCustomer
{
public string data { get; set; } // Array or String?
public string xkey {get;set;}
public Array ykey {get;set;}
public Array labels {get;set;}
}
How can I get JSON like this?
{
"data":[
{
"timeinterval":"2015-10-22T00:00:00",
"Firm":4,
"Firm1":4,
"Firm2":22,
"Firm3":30,
"Firm4":19
},
{
"timeinterval":"2015-10-23T00:00:00",
"Firm":2,
"Firm1":5,
"Firm2":29,
"Firm3":34,
"Firm4":219
}
],
"xkey":"timeinterval",
"ykey":["Firm","Firm1","Firm2","Firm3","Firm4"],
"labels":[" Firm","Firm1","Firm2","Firm3","Firm4"]
}
Firm cannot be hard coded. It all must be dynamic.
My Controller Action:
public JsonResult StatistikaJson()
{
ArrayList arrayList = new ArrayList();
StatistikaByCustomer statisikaObject = new StatistikaByCustomer();
List<Data> listData = new List<Data>();
string jsonTemp = null;
DbDataReader reader = null;
using (var cmd = db.Database.Connection.CreateCommand())
{
if (db.Database.Connection.State == ConnectionState.Closed)
{
db.Database.Connection.Open();
}
cmd.CommandText = "EXEC GetClientConnectsByCustomer #start='" + DateTime.Now.AddMonths(-1).Date.ToString("yyyy-MM-dd") + "',#end='" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "',#interval = 24";
reader = cmd.ExecuteReader();
var tempYkey = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
statisikaObject.ykey = tempYkey.Select(x => x.Replace(" ", "")).ToArray();
if (reader.HasRows)
{
while (reader.Read())
{
string name = reader.GetName(0);
object value = reader.GetDateTime(0);
listData.Add(new Data() { Name = name, Value = value });
for (int i = 1; i < reader.FieldCount - 1; i++)
{
name = reader.GetName(i).Replace(" ", "");
value = reader.GetInt32(i);
listData.Add(new Data() { Name = name, Value = value });
}
//arrayList.Add(JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value)));
jsonTemp += JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value));
jsonTemp += ",";
listData.Clear();
//Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", reader.GetName(0), reader.GetDateTime(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
}
else
{
Debug.WriteLine("No rows found.");
}
statisikaObject.xkey = reader.GetName(0);
statisikaObject.labels = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
reader.Close();
//the number of affected records, if the query returns it var result = cmd.ExecuteNonQuery();
//or a single scalar value //var result = cmd.ExecuteScalar();
//or even a data reader var result = cmd.ExecuteReader();
db.Database.Connection.Close();
}
statisikaObject.data = oSerializer.Serialize(arrayList);
//string json = JsonConvert.SerializeObject(statisikaObject);
//string json = JsonConvert.SerializeObject(l);
return Json(statisikaObject, JsonRequestBehavior.AllowGet);
}
I get JSON, but it's escaped and morris.js doesn't like it.
In my view, I would like to use it like this:
<script type="text/javascript">
$.getJSON('#Url.Action("StatistikaJson")', function (result)
{
new Morris.Line({
element: 'line-example',
data: result.data,
xkey: "timeinterval",
ykeys: result.ykey,
labels: result.labels
});
});
</script>
I can use Json.NET if necessary. If posible, I would like to get ride off the JSON string appending. I would like to have an array and call serialize to get data: json objects in array format that morris.js needs: http://jsbin.com/uqawig/441/embed?js,output
{"data":"{"timeinterval":"2015-10-22T00:00:00","Firm":4,...},{"timeinterval":"2015-10-22T00:00:00","Firm":5,...},...}
ViewModel:
public class StatistikaByCustomer
{
public ArrayList data { get; set; }
public string xkey { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
Controller:
public JsonResult StatistikaJson()
{
StatistikaByCustomer statisikaObject = new StatistikaByCustomer();
ArrayList arrayList = new ArrayList();
List<Data> listData = new List<Data>();
DbDataReader reader = null;
using (var cmd = db.Database.Connection.CreateCommand())
{
if (db.Database.Connection.State == ConnectionState.Closed)
{
db.Database.Connection.Open();
}
cmd.CommandText = "EXEC GetClientConnectsByCustomer #start='" + DateTime.Now.AddMonths(-1).Date.ToString("yyyy-MM-dd") + "',#end='" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "',#interval = 24";
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string name = reader.GetName(0);
object value = reader.GetDateTime(0).ToString("yyyy-MM-dd");
listData.Add(new Data() { Name = name, Value = value });
for (int i = 1; i <= reader.FieldCount - 1; i++)
{
name = reader.GetName(i).Replace(" ", "");
value = reader.GetInt32(i);
listData.Add(new Data() { Name = name, Value = value });
}
arrayList.Add(JsonConvert.SerializeObject(listData.ToDictionary(x => x.Name, y => y.Value)));
listData.Clear();
//Debug.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", reader.GetName(0), reader.GetDateTime(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
}
}
statisikaObject.data = arrayList;
statisikaObject.xkey = reader.GetName(0);
statisikaObject.labels = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToList();
var tempYkey = Enumerable.Range(1, reader.FieldCount - 1).Select(reader.GetName).ToArray();
statisikaObject.ykey = tempYkey.Select(x => x.Replace(" ", "")).ToList();
reader.Close();
db.Database.Connection.Close();
}
return Json(statisikaObject, JsonRequestBehavior.AllowGet);
}
View:
<script type="text/javascript">
$.getJSON('#Url.Action("StatistikaJson")', function (result)
{
new Morris.Line({
element: 'line-example',
data: $.parseJSON("[" + result.data + "]"),
xkey: result.xkey,
ykeys: result.ykey,
labels: result.labels
});
});
</script>
public class Datum
{
public string timeinterval { get; set; }
public int Firm { get; set; }
public int Firm1 { get; set; }
public int Firm2 { get; set; }
public int Firm3 { get; set; }
public int Firm4 { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
public string xkey { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
By putting this code get Serialize json string
var collection = new List<RootObject>();
dynamic collectionWrapper = new
{
people = new RootObject()
{
xkey = "timeinterval",
data = new List<Datum>
{
new Datum()
{
timeinterval = "2015-10-22T00: 00: 00",
Firm = 4,
Firm1= 4,
Firm2= 22,
Firm3= 30,
Firm4= 19
},
new Datum()
{
timeinterval = "2015-10-23T00: 00: 00",
Firm = 2,
Firm1= 5,
Firm2= 29,
Firm3= 34,
Firm4= 219
}
},
ykey = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" }
}
};
var output = JsonConvert.SerializeObject(collectionWrapper);
Edit:
var collection = new StatististikaByCustomer
{
xkey = "timeinterval",
ykey = new List<string>{"Firm","Firm1","Firm2","Firm3","Firm4"},
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
data = new Dictionary<string, string>
{
{ "timeinterval", "2015-10-22T00: 00: 00" },
{ "Firm", "4" },
{ "Firm1", "4" },
{ "Firm2", "22" },
{ "Firm3", "30" },
{ "Firm4", "19" }
}
};
string json = JsonConvert.SerializeObject(collection);
Class:
public class StatististikaByCustomer
{
public string xkey { get; set; }
public Dictionary<string, string> data { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
Update:
var collection = new StatististikaByCustomer
{
xkey = "timeinterval",
ykey = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
labels = new List<string> { "Firm", "Firm1", "Firm2", "Firm3", "Firm4" },
data = new List<Dictionary<string,string>>
{
new Dictionary<string, string>
{
{ "timeinterval", "2015-10-22T00: 00: 00" },
{ "Firm", "4" },
{ "Firm1", "4" },
{ "Firm2", "22" },
{ "Firm3", "30" },
{ "Firm4", "19" }
},
new Dictionary<string, string>
{
{ "timeinterval", "2015-10-23T00: 00: 00" },
{ "Firm", "2" },
{ "Firm1", "5" },
{ "Firm2", "29" },
{ "Firm3", "34" },
{ "Firm4", "219" }
}
}
};
string json = JsonConvert.SerializeObject(collection);
Class:
public class StatististikaByCustomer
{
public string xkey { get; set; }
public List<Dictionary<string, string>> data { get; set; }
public List<string> ykey { get; set; }
public List<string> labels { get; set; }
}
First of all, I know that it's not valid JSON format, but it's my customer web service settings, I need to set QuoteName of Json.Net JsonTextWriter to be false, but I don't know how to do it properly. This is my try:
foreach (var c in a)
{
var jsonobjects = JsonConvert.SerializeObject(c, new JsonTextWriter
{
QuoteName = false
}
);
//Some code that using serialized json object
}
In order to clarify what I want. I need to have Json property name without quotes. Something like that: {Property: "Value"}.
Here is an example:
The class:
public class Address
{
public string Street { get; set; }
public uint Number { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
Serialization logic:
var address = new Address
{
Street = "Fulton Street",
Number = 100,
City = "New York",
ZipCode = "10038",
State = "NY",
Country = "USA"
};
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, address);
}
var json = stringWriter.ToString();
Console.WriteLine(json);
Output:
{
Street: "Fulton Street",
Number: 100,
City: "New York",
ZipCode: "10038",
State: "NY",
Country: "USA"
}
Example:
https://dotnetfiddle.net/zazT1T