Convert Object to Array or list - c#

i have an object that is being passed to me from a json obj, each time it is has different feilds, i am using json.net to parse it, it is parsing it correctly and it is putting it in a list of obj
the format after serialization is:
{
"language": "EN",
"code": "test",
"name": "test",
"value": "TEST",
"id": "2222222222222222"
}
the fields are dynamic it can be up to 50 not just 5
any idea on how to parse it??

If you know the items in above format. you could create an typed object. and then you can use DataContractJsonSerializer like below.
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<myClass>;

Related

How to convert List<model> to string?

I have a list of data and want to convert it into string format like headers and values separated. How can I achieve this in c#?
Expected Result:
dynamic data = {
"values": [
[
5658830,
"Support And Training Services Llc",
"PAM",
"FINNESAND"
],
[
5658831,
"Training Services Llc",
"Bob",
"MCCART"
]
],
"headers": [
"ID",
"ENT_COMPANY1",
"FirstName",
"LastName"
]
}
How to convert in List into above format?
Here's a quick snippet to answer your question, in my own code. You'll still have to propogate the list of objects with whatever it is you have. Just change "object" to the name of your model.
List<string> listOfStrings = new List<string>();
List<object> listOfMyModels = new List<object>();
//fill your list of objects here with whatever it is you're converting to a string
foreach(object myObject in listOfMyModels)
{
string json = JsonConvert.SerializeObject(myObject);
listOfStrings.Add(json);
}
Now you have a list of strings that represent your objects and when needed, you can use the deserialize method to read it.

Format StreamWriter to Write/Append Json in Valid format

Good day,
How can i save/append JSON data in to the File with StreamWriter in a valid JSON format ? Is there a way to Format StreamWriter to append/write file in valid JSON format?
Like :
`[
{ "data1": "data1" },
{ "appended data2": "appended data2" },
{ "appended data3": "appended data3" },
]`
I'm using NewtonJson to serialize JSON from an object and then save it with StreamWriter.
WritableData an_data = new WritableData
{
Titel = tbTitel.Text,
Type = tbType.Text,
Episode = tbEps.Text,
Score = tbScore.Text,
Id = tbID.Text,
TitleEng = tbTitelEng.Text,
Status = tbStatus.Text,
StartDate = tbDateStart.Text,
EndDate = tbDateEnd.Text,
Image = pbImage.ImageLocation
};
string path = SavePath + "\\AnList";
string json = JsonConvert.SerializeObject(an_data, Formatting.Indented);
TextWriter tw = new StreamWriter(path + listFile, true);
tw.WriteLine(json);
tw.Close();
And it is being save as follows :
{
"Titel": "Test1",
"Type": "Movie",
"Episode": "1",
"Score": "6.92",
"Id": "894",
"TitleEng": "Test1",
"Status": "Finished Airing",
"StartDate": "1989-07-15",
"EndDate": "1989-07-15",
"Image": "https://myanimelist.cdn-dena.com/images/anime/5/10193.jpg"
}{
"Titel": "Test2",
"Type": "TV",
"Episode": "153",
"Score": "8.16",
"Id": "223",
"TitleEng": "Test2",
"Status": "Finished Airing",
"StartDate": "1986-02-26",
"EndDate": "1989-04-12",
"Image": "https://myanimelist.cdn-dena.com/images/anime/9/21055.jpg"
}
I couldn't find a way to format it right.
Thank you for your time.
You save your data to the file by appending text to the end. From what magic there'll be [ in the beginning and ] in the end? :)
Why don't you just create an array/list of objects you want to save to the file then serialize it as a whole and save text to the file?
var list = new List<WritableData>();
list.Add(an_data1);
list.Add(an_data2);
//...
list.Add(an_dataN);
var serialized = JsonConverter.SerializeObject(list);
// write to the file with 'overwrite' option, i.e. new StreamWriter(path, false/*!!!*/)
Or another approach is appending text one-by-one like you tried to do. It'll require some tricks:
create text file as [],
then every time you want to save your object (of the same type as the other previous objects), you need to:
open file and remove the last symbol ],
append ,,
append serialized object as you do in your example,
append ]
So every time you'll have a valid json of this, looked like this:
[
{...},
{...},
...
{...}
]
You want to add more properties to your an_data? So add more properties to the class.
var an_data = new WritableData() { //btw, use camelCase in var names
Prop1 = "foo",
Prop2 = "bar"
};
Or use a dictionary:
var an_data = new WritableData() {
AppendableData = new Dictionary<string, object>()
}
an_data.AppendableData["foo"] = "bar";
an_data.AppendableData["bar"] = "foo";
Ideally the serialized class (WriteableData) should contain all fields to be (de)serialized. If it doesn't and you manually append some json data then you won't be able to deserialize that appended data. If you really need to work around this and don't know what data the Json object may contain then consider using Dictionary to store some of that unknown data. But I'd advise to strongly type your serializable json object class. Otherwise you're just inviting hard to maintain code.

Generate JSON schema from dynamic object

I want to extract a JSON schema (as defined here) from an object of type dynamic.
This is the best example I could find.
But JSON.NET's Schema Generator needs to look at an actual class/type to be able to generate a schema.
Anyone have any ideas on how I could extract a schema from a dynamic object?
You can still use JSON.NET to extract a JSON schema from dynamic object. You just need an actual object of type dynamic to be able to do that. Try the following sample:
dynamic person = new
{
Id = 1,
FirstName = "John",
LastName = "Doe"
};
JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator {};
JsonSchema schema = schemaGenerator.Generate(person.GetType());
The generated JSON schema should look like this:
{
"type": "object",
"additionalProperties": false,
"properties": {
"Id": {
"required": true,
"type": "integer"
},
"FirstName": {
"required": true,
"type": [
"string",
"null"
]
},
"LastName": {
"required": true,
"type": [
"string",
"null"
]
}
}
}
If you are using .NET 4.0+ then there is a method System.Web.Helpers.Json.Decode that converts JSON into a dynamic object:
using System.Web.Helpers;
// convert json to a dynamic object:
var myObject = Json.Decode(json);
// or to go the other way and get json from a dynamic object:
string myJson = Json.Encode(myObject);
To reference this assembly you can find it in the Extensions group under Assemblies in Visual Studio 2012.
This should be able solve your problem. If you can include a sample of the JSON it would be clearer.

Comparing JSON response of

Good morning everyone. I have a service which returns me a JSON response (something like below):
{
"sessionid": "AQIC5wM2LY4SfcytTIcteNkTtCVrE8A-AS7VR*",
"Customers": [
{
"id": "4193942846",
"firstname": "Anto",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "ABCD",
},
{
"id": "4193942236",
"firstname": "Dimple",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "AB",
}
],
"Status": "ACTIVE",
"serviceStatus": "SUCCESS",
"Addresses": {
"Address": [
{
"type": "M",
"addr1": "11011, main st",
"addr2": "Apt. 2",
"zipcode": "11011"
}
]
}
}
The above structure varies based on the input I pass to the service. So, I cant contruct one class to deserialize the response. I need to compare (attribute-attribute comparison) this response to a response I already have with me (in a different place).
I tried to do it with dynamic class in C# but no luck so far. Could someone share a better,working approach? Thank you.
You can use JToken.DeepEquals like this:
var response = JObject.Parse(responseJson);
var goldenStandard = JObject.Parse(goldenStandardJson);
if (JToken.DeepEquals(response, goldenStandard))
{
// the two JSONs have the same data
}
Try Json.Net. It supports dynamic structures.
Here is a tutorial:
http://www.codeproject.com/Tips/631586/Dynamic-types-with-JSON-NET
Use this:
https://jsonutil.codeplex.com/
var obj1 = JSONSerializer.Deserialize(jsontext1);
var obj2 = JSONSerializer.Deserialize(jsontext2);
bool Compare(object obj1, object obj2)
{
//if(obj1 is JSONObject && obj2 is JSONObject)
// => typecase and use jsonObj1.Members to iterate over members and compare values recursively
//if JSONArray, then iterate over items and compare
//if anything else... i.e. primitive then compare directly
//else return false;
}
If you are using this JSON response one time, then you can use a dynamic JSON NET types.
But if you are using this JSON structure response some times, then it is preferable to make this response to a c# classes (objects), so you will have a very easy access to it's properties, you just have your c# objects and they have properties and you can simply approach to each field you wish (with intellisense). By the way, it is very easy to copy a JSON response to a C# classes (something like copy paste). Here is how to do that:
http://blogs.msdn.com/b/webdev/archive/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc.aspx

Class Object with Dynamic Structure

Hi Am trying to parse a json Object with Help of C# DataContractJsonSerializer And this is what json may look like
{"user_id":"121","Q1":"question 1","Q2":"question 2","Q3":"question 3"}
And Number of question can be 200- 500,
So I dont want to make a DataContract with 500 Variables to parse this Json, So I was thinking if there is a way where i can call the constructor or something for this class object with a number parameter like this if there are Q1 - Q30 in jSon
Objectparse new_object = new Objectparse(30);
Which will create variables Q1 to Q30 at runtime? and parse the Json
You could use JavaScriptSerializer:
var json = #"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...
and if you are using an older version of .NET than 4.0 and cannot use the dynamic feature you could do this:
var json = #"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
var result = (IDictionary<string, object>)serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...
But let me point out that this is an extremely poor JSON design. The person that designed this class was probably not aware of javascript arrays:
{
"user_id": "121",
"questions": [
{
"key": "Q1",
"value": "question 1"
},
{
"key": "Q2",
"value": "question 2"
},
{
"key": "Q3",
"value": "question 3"
}
]
}
Which could now be serialized into a strongly typed object containing a collections of questions.

Categories