Deserializing Google transliteration in C# using Newtonsoft.Json - c#

As a beginner I tried to deserialize Google transliterator return array. It's a JSON array like this:
[{"ew" : "namaste","hws" : ["नमस्ते","नमसते","नमास्ते",]},]
pretty awesome!
This is my c# class used for deserialization:
[Serializable]
public class googleTransliterator
{
[JsonProperty("ew")]
public String sourceWord { get; set; }
[JsonProperty("hws")]
public String[] transliteratedWords { get; set; }
}
and finally:
using Newtonsoft.Json;
...
...
// return value from google transliteration API is in streamReader
var s = new JsonSerializer();
var gt = (googleTransliterator) s.Deserialize( new StringReader( streamReader.ReadToEnd()), typeof( googleTransliterator));
And what I got is:
Cannot create and populate list type GoogleTransliterator.googleTransliterator.
Any idea what is wrong?

The result is an array of JSON objects ([{...},]) instead of a plain object ({...}).
Your code should work if you change it like this:
var gt = ((googleTransliterator[])s.Deserialize(
new StringReader(streamReader.ReadToEnd()),
typeof(googleTransliterator[])))[0];

Related

Need to deserialize an array of arrays in C#

Need to de-serialize an array of array response to List<Model>
This is my response from other endpoint:
"[[{"BillRateCardId":6992,"ExternalRateCardId":"cd77d9b5-a00e-4696"}]]"
Am using the below line of code to deserialize it to the Model but receiving the error "cant de-serialize that":
List<Model> Res = JsonConvert.DeserializeObject<List<Model>>(Response);
You need to specify the data type that List is expected to contain, either by modeling it as an object:
using Newtonsoft.Json;
var input = "[[{\"BillRateCardId\":6992,\"ExternalRateCardId\":\"cd77d9b5-a00e-4696\"}]]";
var deserialized = JsonConvert.DeserializeObject<List<List<ResponseModel>>>(input);
class ResponseModel
{
public int BillRateCardId { get; set; }
public string? ExternalRateCardId { get; set; }
}
or by using dynamic, but then you lose static type checking:
using Newtonsoft.Json;
var input = "[[{\"BillRateCardId\":6992,\"ExternalRateCardId\":\"cd77d9b5-a00e-4696\"}]]";
var deserialized = JsonConvert.DeserializeObject<List<List<dynamic>>>(input);
Console.WriteLine(JsonConvert.SerializeObject(deserialized));
since you have only one value, you don't need the custom class
var data = JArray.Parse(Response);
long billRateCardId = data.SelectMany(x=>x)
.Where(x =>(string) x["ExternalRateCardId"]=="cd77d9b5-a00e-4696")
.Select(x=>(long) x["BillRateCardId"]).FirstOrDefault();

How to create json dynamically?

I need to create a json dynamically using class. For example following is my json "{'createdDate':['2019-07-20T05:53:28','2019-07-20T05:53:28']}". The class i need is
public class Json
{
public string Key {get;set;}
public List<string> value {get;set;}
}
Creating object and assigning value
var JsonObj = new Json();
JsonObj.key = "createdDate";
JsonObj.Add("2019-07-20T05:53:28");
JsonObj.Add("2019-07-20T05:53:28");
The above class is for single key value pair. But the problem is the key and values are dynamic.may be the key value pairs single or multiple. How can i solve the problem. can anyone try to help me.
I think your problem starts with your nomenclature. Your class is not json, it's merely a list with a name. All you need to do is create your named list, and then serialise it to json using, for example, Newtonsoft.Json. Here's a bit of code :
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ConsoleApp1
{
public class Program
{
public static void Main()
{
NamedList list = new NamedList();
list.Key = "createdDate";
list.Value.Add( "2019-07-20T05:53:28" );
list.Value.Add( "2019-07-20T05:53:29" );
string jsonString = JsonConvert.SerializeObject( list );
}
}
public class NamedList
{
public string Key { get; set; }
public List<string> Value { get; set; }= new List<string>();
}
}

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;
using Newtonsoft.Json;
namespace facebook
{
class Program
{
static void Main(string[] args)
{
var client = new FacebookClient(acc_ess);
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
//jsonstring {"data":[{"target_id":9503123,"target_type":"user"}]}
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
}
public class Datum
{
public Int64 target_id { get; set; }
public string target_type { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
}
}
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[facebook.Program+RootObject]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be
I looked at other posts.
My json looks like this:
{"data":[{"target_id":9503123,"target_type":"user"}]}
To make it clear, in addition to #SLaks' answer, that meant you need to change this line :
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
to something like this :
RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);
As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).
You want to deserialize into a single RootObject.
Can you try to change your json without data key like below?
[{"target_id":9503123,"target_type":"user"}]
That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");
if (response.IsSuccessStatusCode)
{
IEnumerable<RootObject> rootObjects =
awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();
foreach (var rootObject in rootObjects)
{
Console.WriteLine(
"{0}\t${1}\t{2}",
rootObject.Data1, rootObject.Data2, rootObject.Data3);
}
Console.ReadLine();
}
Hope It helps.
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
public partial class tree
{
public int id { get; set; }
public string name { get; set; }
public string sciencename { get; set; }
public int familyid { get; set; }
}
private async void PopulateDataGridView()
{
//For Single object response
tree treeobj = new tree();
treeobj = JsonConvert.DeserializeObject<tree>(Response);
//For list of object response
List<tree> treelistobj = new List<tree>();
treelistobj = JsonConvert.DeserializeObject<List<tree>>(Response);
//done
}

Deserialize JSON data

I've got a JSON data from Twitter API SEARCH.
I'm trying to deserialize these data into objects.
The JSON scheme looks like this:
{
"element": INT,
"element2": STRING,
..
..
"Results":[
{
"user":STRING,
"image":STRING,
..
..
}
]
}
How could I deserialize those JSON elements into objects using JSON Toolkit or something else?
Create a class that matches the JSON schema
public class Data
{
public string Element{get;set;}
public string Element2{get;set;}
public List<Result> Results{get;set;}
}
public class Result
{
public string User{get;set;}
public string Image{get;set;}
}
and use JSON.NET to deserialize
var result = JsonConvert.DeserializeObject<Result>(json);
If you have problems with correct type definition, you can always use dynamic deserialization using Json.Net:
var original = JsonConvert.DeserializeObject<dynamic>(jsonstring);
and then build your desired object based on it (if for example the original one contains overhead information set, and you don't need all of them):
var somepart = new {
E1 = original.element1,
E2 = original.element2
};

How to serialize/deserialize a C# class?

I have an object in Javascript that looks like this
function MyObject(){
this.name="";
this.id=0;
this.....
}
I then stringify an array of those objects and send it to an ASP.Net web service.
At the webservice I want to unserialize the JSON string so I can deal with the data easily in C#. Then, I want to send an array of objects of the same Javascript type(same field names and everything) back to the client. The thing I'm not understanding is how to serialize say this class:
class MyObject{
public string Name;
public int ID;
}
so that the JSON is the same as the above javascript object. And also how to unserialize into the C# MyObject class.
How would I do this easily? I am using Netwonsoft.Json.
Is there some way to turn a JSON string into a List or Array of an object?
with json.net you can use the JsonPropertyAttribute to give your serialized properties a custom name:
class MyObject{
[JsonProperty(PropertyName = "name")]
public string Name;
[JsonProperty(PropertyName = "id")]
public int ID;
}
you can then serialize your object into a List<> like so:
var list = new List<MyObject>();
var o = new MyObject();
list.Add(o);
var json = JsonConvert.SerializeObject(list);
and deserialize:
// json would look like this "[{ "name":"", "id":0 }]"
var list = JsonConvert.DeserializeObject<List<MyObject>>(json);
One thing the WebMethod gives you back is a "d" wrapper which I battled with for hours to get around. My solution with the Newtonsoft/JSON.NET library is below. There might be an easier way to do this I'd be interested to know.
public class JsonContainer
{
public object d { get; set; }
}
public T Deserialize<T>(string json)
{
JsonSerializer serializer = new JsonSerializer();
JsonContainer container = (JsonContainer)serializer.Deserialize(new StringReader(json), typeof(JsonContainer));
json = container.d.ToString();
return (T)serializer.Deserialize(new StringReader(json), typeof(T));
}
You can try the DataContractJsonSerializer Rick Strahl Has a fairly good example.
You tell the serializer the type that you are serializing to and you can decorate the class properties telling them to expect a different name.
As an example:
class MyObject{
[DataMember(name="name")]
public string Name;
[DataMember(name="id")]
public int ID;
}
EDIT: Use
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
ser = new DataContractJsonSerializer(typeof(MyObject));
MyObject obj = ser.ReadObject(ms) as MyObject;
int myObjID = obj.ID;
string myObjName = obj.Name;
}

Categories