How to fix cannot deserialize JSON, confused with the key "1" , "2" - c#

I am confuse with the numbered(the key) newslist (array)
The json string is valid, in nodeJS it managed to output the values that i need.
JSON STRING as is
{
"newsalert": [{
"newslist": {
"1": {
"newsid": "4321",
"headline": "Great White Shark Found",
"newscode": "GWS",
"newstime": "10:04:32"
},
"2": {
"newsid": "8031",
"headline": "Polar Bear Escaped",
"newscode": "PBE",
"newstime": "09:28:03"
}
}
}]
}
C# Code
class MainNews {
public Dictionary<string, newslist[]> newsalert { get; set; }
}
class newslist {
public int newsid { get; set; }
public string headline{ get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}
static void ShowObject(MainNews obj) {
foreach (var item in obj.news.Values.ElementAt(0)) {
MessageBox.Show(item.headline);
}
}
private void BtnTest_Click(object sender, RoutedEventArgs e) {
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var xnews = JsonConvert.DeserializeObject<MainNews>(jsonstring);
ShowObject(xnews);
}
Error
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON array because the type requires a JSON object

You are missing a step betwwen your root and the Dictionary.
newsalert is a collection on a object with a property name newslist.
That this is your dictionary.
public class MainNews
{
public List<NewAlert> newsalert { get; set; }
}
public class NewAlert
{
public Dictionary<int, NewItem> newslist { get; set; }
}
public class NewItem
{
public string newsid { get; set; }
public string headline { get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}
You can simply :
string input = #"{
""newsalert"": [{
""newslist"": {
""1"": {
""newsid"": ""4321"",
""headline"": ""Great White Shark Found"",
""newscode"": ""GWS"",
""newstime"": ""10:04:32""
},
""2"": {
""newsid"": ""8031"",
""headline"": ""Polar Bear Escaped"",
""newscode"": ""PBE"",
""newstime"": ""09:28:03""
}
}
}]
}";
var result = JsonConvert.DeserializeObject<MainNews>(input);
result.newsalert.SelectMany(x=> x.newslist.Values).Dump();
Live Demo: https://dotnetfiddle.net/Ar5ocP

Related

Parse (Deserialize) JSON with dynamic keys (C#)

I want to parse the JSON on the bottom. Till now I always have the static key for the variables, but in this example, the keys are always changing. Here the "58e7a898dae4c" and "591ab00722c9f" could have any value and change constantly. How can I get the value of the elements of the set to be able to reach the PreviewName value?
{
"key": "gun",
"objects": [
{
"name": "AK47",
"sets": {
"58e7a898dae4c": {
"set_id": "58e75660719a9f513d807c3a",
"preview": {
"resource": {
"preview_name": "preview.040914"
}
}
},
"591ab00722c9f": {
"set_id": "58eba618719a9fa36f881403",
"preview": {
"resource": {
"preview_name": "preview.81a54c"
}
}
}
}
}
]
}
public class Object
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("sets")]
public Dictionary<string, Set> Sets { get; set; }
}
public class Set
{
[JsonProperty("set_id")]
public string SetId { get; set; }
[JsonProperty("preview")]
public Preview Preview { get; set; }
}
public class Preview
{
[JsonProperty("resource")]
public ResourcePreview Resource { get; set; }
}
public class ResourcePreview
{
[JsonProperty("preview_name")]
public string PreviewName { get; set; }
}
var root = JsonConvert.DeserializeObject<RootObject>(json);
string previewName1 = root.Objects[0].Sets["58e7a898dae4c"].Preview.Resource.PreviewName;
string previewName2 = root.Objects[0].Sets["591ab00722c9f"].Preview.Resource.PreviewName;
you don't need to deserialize, you can parse
var jsonParsed=JObject.Parse(json);
string[] previewNames= ((JArray)jsonParsed["objects"])
.Select(v => ((JObject)v["sets"]))
.Select(i=>i.Properties().Select(y=> y.Value["preview"]["resource"])).First()
.Select(i=> (string) ((JObject)i)["preview_name"]).ToArray();
result
preview.040914
preview.81a54c

Deserialize post request

im trying to deserilize this code on Windows Forms with C#, and i need to insert on a table the "response" foreach register, but i dont know how to access to every response section.
[
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "83240",
"asentamiento": "Fuentes Del Mezquital",
"tipo_asentamiento": "Colonia",
"municipio": "Hermosillo",
"estado": "Sonora",
"ciudad": "Hermosillo",
"pais": "México"
}
},
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "83240",
"asentamiento": "Las Quintas",
"tipo_asentamiento": "Colonia",
"municipio": "Hermosillo",
"estado": "Sonora",
"ciudad": "Hermosillo",
"pais": "México"
}
},
]
the provider gave me this code, and if you see in the code below only open the console in case that an error occours. but in the else clausule i need to access in the response to get the params for each register.
{
class Program
{
static void Main(string[] args)
{
string endpoint_sepomex = "http://api-sepomex.hckdrk.mx/query/";
string method_sepomex = 'info_cp/';
string variable_string = '?type=simplified';
string url = endpoint_sepomex + method_sepomex + variable_string;
var response = new WebClient().DownloadString(url);
dynamic json = JsonConvert.DeserializeObject(response);
foreach(var i in json)
{
if(i.error)
{
Console.WriteLine("Algo salio mal");
}
else
{
Console.WriteLine("Todo salio bien");
}
}
}
}
}
You would want to create a model. You can use a site like Json2CSharp to help with the process:
public class Response {
[JsonProperty("cp")]
public string Cp { get; set; }
[JsonProperty("asentamiento")]
public string Asentamiento { get; set; }
[JsonProperty("tipo_asentamiento")]
public string TipoAsentamiento { get; set; }
[JsonProperty("municipio")]
public string Municipio { get; set; }
[JsonProperty("estado")]
public string Estado { get; set; }
[JsonProperty("ciudad")]
public string Ciudad { get; set; }
[JsonProperty("pais")]
public string Pais { get; set; }
}
public class BaseResponse {
[JsonProperty("error")]
public bool Error { get; set; }
[JsonProperty("code_error")]
public int CodeError { get; set; }
[JsonProperty("error_message")]
public object ErrorMessage { get; set; }
[JsonProperty("response")]
public Response Response { get; set; }
}
Then you can deserialize like so:
var obj = JsonConvert.DeserializeObject<List<BaseResponse>>(response);

How to insertmany() JSON Array in mongodb using C#

anyone know how to insert this json array into mongodb using insertmany() and C# ??
i cant find any good source for this problem
MongoCollectionBase.InsertMany expects an IEnumerable<TDocument>.
So you need to deserialize your data json element to TDocument[], (Datum) and then pass that array to InsertMany.
Based on the below json, which is different from your screenshot
{
"data": [
{
"pulsa_code": "alfamart100",
"pulsa_op": "Alfamart Voucher",
"pulsa_nominal": "Voucher Alfamart Rp 100.000",
"pulsa_price": 100000,
"pulsa_type": "voucher",
"masaaktif": "0",
"status": "active"
}
]
}
This should work
//...
public class Datum
{
public string pulsa_code { get; set; }
public string pulsa_op { get; set; }
public string pulsa_nominal { get; set; }
public double pulsa_price { get; set; }
public string pulsa_type { get; set; }
public string masaaktif { get; set; }
public string status { get; set; }
public double harga { get; set; }
}
public class PriceListPrepaidModel
{
public List<Datum> data { get; set; }
}
public class PriceList : BaseDatabase
{
//NOTE: The strongly typed IMongoCollection<T> must be the same type as the entities passed to InsertMany
private IMongoCollection<Datum> _pricelistCollection;
//private IMongoCollection<PriceListPrepaidModel> _pricelistCollection;
public PriceList(IServiceProvider serviceProvider)
{
_pricelistCollection = DB.GetCollection<PriceListPrepaidModel>("price_prepaid");
}
public ResponseModel<string> PriceListPrepaidTest(PriceListPrepaidRequest request)
{
var entityResult = new ResponseModel<string>();
try
{
Console.WriteLine(response.Content);
//Desirialize to your model class, not JObject
var model = JsonConvert.DeserializeObject<PriceListPrepaidModel>(message.AsString);
foreach (var item in model.data)
{
item.pulsa_price = (int)item.pulsa_price + 200;
}
//Insert the array of `Datum`
_pricelistCollection.InsertMany(model.data);
entityResult.Value = JsonConvert.SerializeObject(model.data);
entityResult.Status = true;
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
}

how to De-serialize the JSON file by c#

if the key is different, how do i deserialize the JSON file, key from key1 to keyN ? when i using python it's very easy,
import pandas as pd
myJson = pd.json.loads(json)
just used two lines code, but when i use C#, it's very hard to me. thanks.
i tried:
1. visual studio -> Edit -> Paste Special -> Paste Json as Classes, it will generate many class for every item key, which is too bad for me, because my key maybe from key1 to key 1000.
public class Rootobject
{
public Key1 key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
}
2.now i used below method, but i still think it's not easy as python.
JObject items = JObject.Parse(json);
foreach(var item in items)
{
JObject v = JObject.Parse(item.Value.ToString());
foreach(KeyValuePair<string, JToken> property in v)
{ //do something}
}
json string:
{
"key1":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key2":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key3":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v": {
"id":"090",
"Name":"tom",
"D":{"id":"7890"}
}
}
}
}
}
Use DeserializeObject and get a dictionary from it:
var r = JsonConvert.DeserializeObject<Dictionary<string, Key>>(txt);
Declare your classes:
public class Key
{
public int id { get; set; }
public string name { get; set; }
public AllocationInfo AllocationInfo { get; set; }
}
public class AllocationInfo
{
public string State { get; set; }
public string Name { get; set; }
public TModel TModel { get; set; }
}
public class TModel
{
public string Name { get; set; }
public string key { get; set; }
public v v { get; set; }
}
public class v
{
public string id { get; set; }
public string name { get; set; }
}
You pasted the entire json when you used the paste special. But I think you only want to generate one class for all your keyN objects. You can then just use Newtonsoft to deserialize the json to a list.
var myKeys = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyN>>(json);

Deserialize JSON object with unknown name

I have json like this
{
"result": "success",
"response_code": 200,
"message": "",
"collection": {
"<channel_id>": {
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
},
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
}
}
}
}
which channel_id and category_id is not a fixed name. How do I can deserialize it on C#?
Assuming everything else is pretty much fixed, you might try to model this along these lines:
public class MyJsonClass
{
public String Result { get; set; }
public int Response_Code { get; set; }
public String Message { get; set; }
public Dictionary<String, Dictionary<String, JsonCategoryDescription>>
Collection { get; set; }
}
public class JsonCategoryDescription
{
public String Id_Category { get; set; }
public String Name { get; set; }
public String Date_Created { get; set; }
}
Then you deserialize it as follows (System.Web.Script.Serialization namespace):
var result = new JavaScriptSerializer().Deserialize<MyJsonClass>(myJsonString);
and you can access specific fields, like so:
result.Collection[SOME_CHANNEL_ID][SOME_CATEGORY_ID].Name = "XXX";
If you use Dynamic instead of a static type you can have a variable schema of your JSON file. Here is a working console program:
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("file.json");
dynamic obj = JObject.Parse(json);
Console.WriteLine(obj.collection.channel_id);
}
}

Categories