Deserialize Json with no name Fields and Format string, array - c#

I have the following json object:
[
"sd",
[
"sdg\u0026e",
"sdlc",
"sdccu",
"sdsu webportal",
"sdsu",
"sdsu blackboard",
"sdcc",
"sd card",
"sdn",
"sdro"
]
]
Obtained from google suggest with this URL:
http://suggestqueries.google.com/complete/search?output=firefox&hl=en&q=sd
I have tried deserializing it like this:
dynamic objson = JsonConvert.DeserializeObject(res);
But it is not useful because I need it into a class object.
And also using types:
public class SuggestClass
{
public string search { get; set; }
public string[] terms { get; set; }
}
var result = JsonConvert.DeserializeObject<SuggestClass>(res);
But it always throw exception.
I do not know how can I do it without having name fields.
EDIT:
Another JSON:
["text",["textura","textos bonitos","texto argumentativo","textos","textos de amor","texto expositivo","texturas minecraft","textos de reflexion","texture pack minecraft","textos en ingles"]]

That's tricky...
But since it's an array, you could create a factory method to parse SuggestClass out of given JArray.
public void SomeMethod()
{
string json =
"[\"sd\",[\"sdg\u0026e\",\"sdlc\",\"sdccu\"" +
",\"sdsu webportal\",\"sdsu\",\"sdsu blackboard\","+
"\"sdcc\",\"sd card\",\"sdn\",\"sdro\"]]";
var factory = new Factory();
var suggest = factory.Create(json);
Console.WriteLine(suggest);
}
public class Factory
{
public SuggestClass Create(string json)
{
var array = JArray.Parse(json);
string search = array[0].ToString();
string[] terms = array[1].ToArray().Select(item => item.ToString()).ToArray();
return new SuggestClass {Search = search, Terms = terms};
}
}
public class SuggestClass
{
public string Search { get; set; }
public IEnumerable<string> Terms { get; set; }
public override string ToString()
{
return string.Format("Search={0},Terms=[{1}]",
Search, string.Join(",", Terms));
}
}
Would print to console:
Search=sd,Terms=[sdg&e,sdlc,sdccu,sdsu webportal,sdsu,sdsu blackboard,sdcc,sd card,sdn,sdro]
And the other JSON you provided:
Search=sd,Terms=[sdg&e,sdlc,sdccu,sdsu webportal,sdsu,sdsu blackboard,sdcc,sd card,sdn,sdro]
Search=text,Terms=[textura,textos bonitos,texto argumentativo,textos,textos de amor,texto expositivo,texturas minecraft,textos de reflexion,texture pack minecraft,textos en ingles]

Just used the JSON visualizer in visual studio. This is how it looks like.
It is an array of multiple types. The following code can be used to parse it. But it is not perfect yet.
var objson = JsonConvert.DeserializeObject<object[]>(res);
So I think #Mikko answer has a better approach..

Related

Serialize custom type to JSON

class Program
{
static void Main(string[] args)
{
JSONClass jsonClass = new JSONClass();
JSONElement el = new JSONElement
{
A = 5,
B = "test1"
};
JSONElement el2 = new JSONElement
{
A = 3,
B = "test2"
};
jsonClass.JSONList.Add(el);
jsonClass.JSONList.Add(el2);
var output = JsonSerializer.Serialize<JSONClass>(jsonClass);
Console.WriteLine(output);
}
}
public class JSONClass
{
public List<JSONElement> JSONList = new List<JSONElement>();
}
public class JSONElement
{
public int A { get; set; }
public string B { get; set; }
}
This code returns {} which means that JsonSerializer.Serialize failed to do what it supposed to do. I imagine its because its not smart enough to handle custom types. And here is my question, how to do it. Internet is full of articles how to write custom converters etc, but none of them mention custom types.
Your JSONList member is a public field - whereas JsonSerializer looks for properties.
Change your code for JSONClass to this:
public class JSONClass
{
public List<JSONElement> JSONList { get; } = new List<JSONElement>();
}
The output is then:
{"JSONList":[{"A":5,"B":"test1"},{"A":3,"B":"test2"}]}
The bigger lesson to learn here is not to assume that the mistake is in the library you're using. Always start with an expectation that the problem is in your own code. Sometimes you'll find it really is in the library or system code (or in the compiler etc) but in my experience that's relatively rare.

Deserialize JSON to list with unknown object name in C#

I want to deserialize following JSON.
The problem is that the objects "ANDE" & "DAR" can change.
Means the objects are unknown and change depending on the JSON i wanna deserialize.
About 8000 different objects (ANDE, DAR, ...) need to be deserialized.
{"ANDE":
{"chart":[
{"date":"20180914","minute":"09:30"},{"date":"20180914","minute":"13:30"}]},
"DAR":
{"chart":[
{"date":"20180914","minute":"09:30"},{"date":"20180914","minute":"13:30"}]}}
I get the data by HTTP response and want to put into a List:
HttpResponseMessage response = client.GetAsync(API_PATH).GetAwaiter().GetResult();
List historicalDataList = response.Content.ReadAsAsync<List<HistoricalDataResponse>>().GetAwaiter().GetResult();
The HistoricalDataResponse class looks like:
public class HistoricalDataResponse
{
public string date { get; set; }
public string minute { get; set; }
}
How can i deserialize this kind of JSON with unknown objects in C#?
Any help is highly appreciated.
Then you should use a dynamic variable:
dynamic ReturnValue = JsonConvert.DeserializeObject(jsonstring);
note that as in dynamic objects, properties are determined after being assigned in runtime, so you will not get a drop down menu in design time, and also as its properties are unknown in design time, and property you test in design time even if its not correct, you wont get an error, and you will get the error in runtime when it is assigned.
dynamic ReturnValue = JsonConvert.DeserializeObject(jsonstring);
try
{
var a = ReturnValue.ANDE; // will work if it has ANDE property.
// do what you would do with ANDE
}
catch{}
try
{
var a = ReturnValue.DAR; // will work if it has DAR property.
// do what you would do with DAR
}
catch{}
Use a dictionary with string as key type :
void Main()
{
var client = new HttpClient();
HttpResponseMessage response = client.GetAsync("url").GetAwaiter().GetResult();
var json = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var result = JsonConvert.DeserializeObject<Dictionary<string, DateResponse>>(json);
foreach (var element in result)
{
var key = element.Key; // ANDE
foreach (var item in element.Value.Chart)
{
var date = item.date;
var minute = item.minute;
}
}
}
public class DateResponse{
public List<HistoricalDataResponse> Chart { get; set; }
}
public class HistoricalDataResponse
{
public string date { get; set; }
public string minute { get; set; }
}

How can i see if my JSON contains a certain value and then compare it?

var Name = "Resources.myjson.json";
var NameJSON = new System.IO.StreamReader(typeof(Strings).GetTypeInfo().Assembly.GetManifestResourceStream(Name)).ReadToEnd();
var ParsedBrandJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<TheInfo>(NameJSON);
await JsonCS.LoadJson(ParsedBrandJSON);
And on the page:
static public class TheInfoJSON
{
static public TheInfo Data { get; set; }
static public async Task LoadJson(Data JSON)
{
Data = JSON;
}
}
and
public class TheInfo
{
public List<TheName> TheName { get; set; } = new List<TheName>();
}
My json:
{
"TheInfo":[
{
"TheName": ["Martin", "Jonas", "Alex", "Oscar"]
}
]
}
When i now try to compare how can i see if my JSON contains a certain object and then store that as a single TheName? Is it possible to do it in the same cast?
var TheNameDataFromOtherPage = OtherPage.TheName; //Here i gather the name from another page that i will compare with the JSON
//Wrong syntax
bool DoTheyMatch = TheNameDataFromOtherPage == TheInfoJSON.Data.TheName.Contains("Alex");
This is now wrong syntax because i cant compare the value to a bool. How can i get out the data i find and then instead of having TheInfoJSON.Data.TheName.Contains("Alex"); as a bool, back to a single value of TheName containing "Alex" so I can create a bool out of the two values to see if the JSON has it or not.
I tried to add something along the lines like this after the contains(): as TheInfo.TheName but that isnt the correct syntax either.
bool DoTheyMatch = TheInfoJSON.Data.TheName.Contains(TheNameDataFromOtherPage);

Deserializing Complex Json Object to Dictionary

I am having some trouble deserializing a Json string to use in an api wrapper I am currently writing. This is the json string in question:
{
"Search":[
{
"Title":"Clerks.",
"Year":"1994",
"imdbID":"tt0109445",
"Type":"movie"
},
{
"Title":"Clerks II",
"Year":"2006",
"imdbID":"tt0424345",
"Type":"movie"
}
]
}
This is the method I am currently using to process it.
public static Dictionary<string, string> FetchTitlesListDictionary(string searchQuery)
{
string searchResult = SendRequest(new[] { "?s=", searchQuery });
JObject parser = JObject.Parse(searchResult);
var movieDictionary = new Dictionary<string, string>();
for (int i = 0; i < parser["Search"].Count(); i++)
{
if (!movieDictionary.ContainsKey((string)parser["Search"][i]["imdbID"]))
{
movieDictionary.Add((string)parser["Search"][i]["imdbID"],
(string)parser["Search"][i]["Title"]);
}
}
return movieDictionary;
}
Even though the code above works, I feel it could, somehow, be made simpler.
How would I go about achieving this?
Thanks!
var obj = JsonConvert.DeserializeObject<RootObject>(searchResult);
public class Search
{
public string Title { get; set; }
public string Year { get; set; }
public string imdbID { get; set; }
public string Type { get; set; }
}
public class RootObject
{
public List<Search> Search { get; set; }
}
If you really want to convert the RootObject to a dictionary, you can use
var movieDictionary = obj.Search.ToDictionary(s => s.imdbID, s => s.Title);
PS: see this site
Well, if you're open to not using the default serializer, I would just open up the package manager console and type
Install-Package ServiceStack.Text
Then it becomes as easy as
var myDictionary = JsonObject.Parse(myJsonString)
.ArrayObjects("Search")
.ToDictionary(key => key.Get("imdbID"), value => value.Get("Title"));
There might be a similar and just as simple way to do it with the newtonsoft serializer, but honestly I never use it, so i'm not sure.
Also same thing as EZI's answer, it's also really easy if you have the objects he created, then you can just
var myObject = myJsonString.FromJson<RootObject>();
//if you want the dictionary it's the same thing, standard linq
var dictionary = myObject.Search.ToDictionary(x => x.imdbId, x => x.Title);
but if all you need is a dictionary, I would just use the above method, it's fast and easy.

How do I incrementally serialize and deserialize JSON with ServiceStack?

What I have is this:
string json = #"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
How do I read the fields until I'm at 'object', then serialize the whole 'object' into a .NET type and then continue parsing?
Define your types:
public class Object
{
public int t { get; set; }
public string whatever { get; set; }
public string str { get; set; }
}
public class RootObject
{
public int number { get; set; }
public Object object { get; set; }
}
Then just deserialize it:
string json = #"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
//do what you want
UPDATE
You didn't say it's dynamic, for such parsing there is many solutions.
Check the following:
Using JSON.NET for dynamic JSON parsing
Using C# 4.0 and dynamic to parse JSON
Deserialize JSON into C# dynamic object?
Parse JSON block with dynamic variables
Turning JSON into a ExpandoObject
To handle a dynamic type: use dynamic, to handle dynamic data such as XML or JSON use ExpandoObject.
UPDATE 2
Using Anonymous types to deserialize JSON data
UPDATE 3
Will this work for you:
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = SimpleJson.DeserializeObject<IDictionary<string, object>>(json);
var yourObject = deserialized["object"] as IDictionary<string, object>;
if (yourObject != null)
{
var tValue = yourObject.GetValue("t");
var whateverValue = yourObject.GetValue("whatever");
var strValue = yourObject.GetValue("str");
}
public static object GetValue(this IDictionary<string,object> yourObject, string propertyName)
{
return yourObject.FirstOrDefault(p => p.Key == propertyName).Value;
}
Final result:
Or change to the following
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
UPDATE 4 - SERVICE STACK
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = JsonObject.Parse(json);
var yourObject = deserialized.Get<IDictionary<string, object>>("object");
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
Result:
Look at ServiceStack's Dynamic JSON Parsing:
var myPoco = JsonObject.Parse(json)
.GetUnescpaed("object")
.FromJson<TMyPoco>();
This works for deserializing, I will update once I got serializing.
foreach(KeyValuePair<String,String> entry in JsonObject.Parse(json))
{
}
Edit: Looks like this only works for json objects. I still don't know how to iterate over JsonArrayObjects

Categories