incorrect parsing of JSON into ArrayList - json

I am trying to fill an Android Spinner given some sql generated json in a PHP.
I have already generated with PHP a JSON like this:
{
num: [
{
id: 123
},
{
id: 456
}
]
}
I need to get the Android Client Spinner populated with 123 and 456, but I just get the Spinner populated with only one line (that incidentally contains two ids), I did this:
ArrayList<String> LineArray = new ArrayList<String>();
LineArray.add(responsej.optString("num"));
Spinner myspinner;
myspinner = (Spinner) findViewById(R.id.my_spinner) ;
myspinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, LineArray));
responsej is the JSONObject that I get with JsonHttpResponseHandler. Any suggestions how to get the Client to understand that each id should get populated?

Make to Model classes like this
Num.class
public class Num
{
public int id { get; set; }
}
SpinnerData.class
public class RootObject
{
public List<Num> num { get; set; }
}
Then parse data to this model

Related

change web api return type

I am working on a web api project and I want to return aspecific json type. I am returning two different arrays but I want it to be as the type I put below.
Snippet from my controller
public IHttpActionResult GetNOX(){
-------
List<ListCreator> lisss = new List<ListCreator>();
lisss.Add(new ListCreator(ısavg, ossbavg, kadavg, benzinavg, dolumavg, harfiyatavg, madenavg));
return Ok(lisss);
}
------------------
public class ListCreator
{
public List<double> avg = new List<double>();//ArayLists which contains the industrial sectors and their gas emissions
public List<string> names = new List<string>();
public ListCreator(double ısınma, double osb, double kad, double benzin, double dolum, double harfiyat, double maden)//Consructor
{
avg.Add(ısınma);//Adds sector names to arraylist
avg.Add(osb);
avg.Add(kad);
avg.Add(benzin);
avg.Add(dolum);
avg.Add(harfiyat);
avg.Add(maden);
names.Add("Isinma");
names.Add("OSB");
names.Add("KAD");
names.Add("Benzin");
names.Add("Dolum");
names.Add("Harfiyat");
names.Add("Maden");
}
My output is
[{"avg":[384925464640.5,1215183866.964,255.0,85284076.039996013],"names": ["Isinma","OSB","Benzin","Harfiyat"]}]
I want it to be in the form
data: [
['Isınma Kaynaklı', 56.0],
['OSB', 21.0],
['KAD', 2.3],
['Benzin İstasyonu', 25.0],
['Dolum Tesisleri', 18.6],
['Harfiyat Alanları', 11.8],
['Maden Taş Ocakları', 12.7]
]
Seems like what you want is to associate a name with a avg.
What I would do here is create a new class with those two fields and encapsulate what you are trying to model.
Something like
public class Model
{
public string Name { get; set; }
public double Average { get; set; }
}
Then in your controller you can return a List
public IHttpActionResult Get()
{
List<Model> models = new List<Model>
{
new Model
{
Name = "Name",
Average = "10.0"
}
};
return models;
}
Your JSON on the client will look something like (depending what json formatter you are using)
[
{ name: 'name', average: '10.0' }
]

asp.net mvc 5 Dapper Json is mapping the whole model class

I am using Dapper in my ASP.NET MVC 5 application and in my query I only want 2 fields to return but the Json returns all of the fields. This is my model
public class thread
{
[Key]
public int id { get; set; }
public int? profileID { get; set; }
public int numberkeeper { get; set; }
public int? photocount { get; set; }
}
This is my controller..
[ResponseType(typeof(thread))]
public IHttpActionResult Getstream()
{
string Connectionstring = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
{
sqlConnection.Open();
var statevi = sqlConnection.Query<thread>("Select top 5 id,numberkeeper from threads").ToList();
if (statevi == null)
{
return NotFound();
}
return Ok(statevi);
}
}
That code returns Json as it is using .Net Web API,as you can see from the query I only want 2 fields returned. When I run it and see the Json it displays all fields (4) and off course the 2 fields not selected show up as null . I wanted so that the Json only shows the returnn of id and numberkeeper
Create a View Model class:
public class ThreadViewModel
{
public int id { get; set; }
public int numberkeeper { get; set; }
}
Let Dapper know you want it to create the ThreadViewModel for you:
var statevi = sqlConnection.Query<ThreadViewModel>("Select top 5 id,numberkeeper from threads").ToList();
This way you both query the database for the relevant properties and return just them to the client (without Dapper creating the full object with nulls).
If you create a new model that exposes the only two members that you want to render, that will prevent Web API from returning back additional JSON.
You could also convert the data after loading it into a new anonymous model using LINQ.
return Ok(statevi.Select(s => new { s.id, s.numberkeeper }));
If you want to keep the same model, but suppress null valued members Web API allows you to configure the JSON formatting to exclude null properties.
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
If you want to use 2 or selected rows from query then you can use query method and extension method...
1. LINQ query method
using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
{
sqlConnection.Open();
var statevi = sqlConnection.Query<thread>("Select top 5 id,numberkeeper from threads").ToList();
if (statevi == null)
{
return NotFound();
}
var result = (from d in statevi
select new { d.id, d.numberkeeper }).ToList();
return Ok(result);
}
Extension Method: change this syntax to result of query method of above
var result = query.Select(d => new { d.Id, d.Title }).ToList();
both will give result same.
let me tell if it is working fine for your project or not.

Ignore parsing errors during JSON.NET data parsing

I have an object with predefined data structure:
public class A
{
public string Id {get;set;}
public bool? Enabled {get;set;}
public int? Age {get;set;}
}
and JSON is supposed to be
{ "Id": "123", "Enabled": true, "Age": 23 }
I want to handle JSON error in positive way, and whenever server returns unexpected values for defined data-types I want it to be ignore and default value is set (null).
Right now when JSON is partially invalid I'm getting JSON reader exception:
{ "Id": "123", "Enabled": "NotABoolValue", "Age": 23 }
And I don't get any object at all.
What I want is to get an object:
new A() { Id = "123", Enabled = null, Age = 23 }
and parsing warning if possible.
Is it possible to accomplish with JSON.NET?
To be able to handle deserialization errors, use the following code:
var a = JsonConvert.DeserializeObject<A>("-- JSON STRING --", new JsonSerializerSettings
{
Error = HandleDeserializationError
});
where HandleDeserializationError is the following method:
public void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
errorArgs.ErrorContext.Handled = true;
}
The HandleDeserializationError will be called as many times as there are errors in the json string. The properties that are causing the error will not be initialized.
Same thing as Ilija's solution, but a oneliner for the lazy/on a rush (credit goes to him)
var settings = new JsonSerializerSettings { Error = (se, ev) => { ev.ErrorContext.Handled = true; } };
JsonConvert.DeserializeObject<YourType>(yourJsonStringVariable, settings);
Props to Jam for making it even shorter =)
There is another way. for example, if you are using a nuget package which uses newton json and does deseralization and seralization for you. You may have this problem if the package is not handling errors. then you cant use the solution above. you need to handle in object level. here becomes OnErrorAttribute useful. So below code will catch any error for any property, you can even modify within the OnError function and assign default values
public class PersonError
{
private List<string> _roles;
public string Name { get; set; }
public int Age { get; set; }
public List<string> Roles
{
get
{
if (_roles == null)
{
throw new Exception("Roles not loaded!");
}
return _roles;
}
set { _roles = value; }
}
public string Title { get; set; }
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
see https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm

JSON property with hyphen in it in ServiceStack

I have some JSON formed like this:
{
"snippet-format":"raw",
"total":1,"start":1,
"page-length":200, ...
}
I have a C# DTO with members called Total, Start etc. These are successfully having the values from the above placed in to them. I don't know how to name properties for the snippet-format and page-length JSON items above though.
I've tried SnippetFormat and Snippet_Format to no avail.
Could someone please point me in the right direction.
Also, if a value happens to be a W3C xs:dateTime string, is there a type I can use that ServiceStack will automatically populate for me?
Thanks in advance.
Checked into the next version of ServiceStack.Text v3.9.43+, the Lenient property convention now supports hyphened properties, so you will be able to do:
public class Hyphens
{
public string SnippetFormat { get; set; }
public int Total { get; set; }
public int Start { get; set; }
public int PageLength { get; set; }
}
JsConfig.PropertyConvention = JsonPropertyConvention.Lenient;
var json = #"{
""snippet-format"":""raw"",
""total"":1,
""start"":1,
""page-length"":200
}";
var dto = json.FromJson<Hyphens>();
Assert.That(dto.SnippetFormat, Is.EqualTo("raw"));
Assert.That(dto.Total, Is.EqualTo(1));
Assert.That(dto.Start, Is.EqualTo(1));
Assert.That(dto.PageLength, Is.EqualTo(200));
In the meantime you will have to parse it dynamically, e.g:
var map = JsonObject.Parse(json);
Assert.That(map["snippet-format"], Is.EqualTo("raw"));
Assert.That(map["total"], Is.EqualTo("1"));
Assert.That(map["start"], Is.EqualTo("1"));
Assert.That(map["page-length"], Is.EqualTo("200"));

How do I use restsharp to read a Json array

I need to read the following piece of code using RestSharp. My problem is how to get the array in the proper structure. How do I need to setup the class that will contain the object to make this work properly?
I would like to deserialize the object "0" and "1" in a List of type AcUserInfo.
Thanks a lot.
Andrea
{
"0":{
"id":"2",
"subscriberid":"2",
"cdate":"2012-09-28 16:49:06",
"sdate":"2012-09-28 16:49:06",
"first_name":"Al",
"last_name":"",
"email":"test#verizon.net"
},
"1":{
"id":"29",
"subscriberid":"29",
"cdate":"2012-10-02 15:08:29",
"sdate":"2012-10-02 15:08:29",
"first_name":"Mark",
"last_name":"",
"email":"test2#verizon.net"
},
"result_code":1,
"result_message":"Success: Something is returned",
"result_output":"json"
}
Here's the class I've created:
public class SubscriberList {
public int result_code { get; set; }
public string result_message { get; set; }
public string result_output { get; set; }
public List<AcUserInfo> row { get; set; }
SubscriberList(){
row = new List<AcUserInfo>();
}
}
Your JSON data does not contain an array, and therefore cannot be deserialized to a List<>.
Either convert your JSON to something like this:
{
[{
"id":"2",
"subscriberid":"2",
"cdate":"2012-09-28 16:49:06",
"sdate":"2012-09-28 16:49:06",
"first_name":"Al",
"last_name":"",
"email":"test#verizon.net"
},
{
"id":"29",
"subscriberid":"29",
"cdate":"2012-10-02 15:08:29",
"sdate":"2012-10-02 15:08:29",
"first_name":"Mark",
"last_name":"",
"email":"test2#verizon.net"
}],
"result_code":1,
"result_message":"Success: Something is returned",
"result_output":"json"
}
Or if you always only have the "0" & "1" element then change your SubscriberList class to match it.