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.
Related
So I have below call to a method where my argument is a json string of this type
var jsonWithSearchData = await querySearchData(jsonOut);
jsonOut ->
[
{
"data": {
"_hash": null,
"kind": "ENY",
"id": "t123",
"payload": {
"r:attributes": {
"lok:934": "#0|I"
},
"r:relations": {
"lok:1445": "15318",
"lok:8538": "08562"
},
"r:searchData": "",
"r:type": [
"5085"
]
},
"type": "EQT",
"version": "d06"
}
}
]
The querySearchData() returns me two list something like this :["P123","P124","P987"] and ["Ba123","KO817","Daaa112"]
I want to add this list in my r:searchData key above. The key inside my searchData i.e. r:Porelation and ClassA and ClassB remains static. So I would like my searchData in my input Json to finally become something like this.
"r:searchData": {
"r:Porelation":{
"ClassA": ["P123","P124","P987"],
"ClassB": ["Ba123","KO817","Daaa112"]
}
},
How can I do this? What I tried:
JArray jfinObject = JArray.Parse(jobjects);
jfinObject["r:searchData"]["r:relations"]["ClassA"] = JArray.Parse(ListofCode.ToString());
And I get below error:
System.Private.CoreLib: Exception while executing function: Function1.
Newtonsoft.Json: Accessed JArray values with invalid key value:
"r:searchData". Int32 array index expected.
There are a few ways you can add a node/object/array to existing json.
One option is to use Linq-to-Json to build up the correct model.
Assuming you have the json string described in your question, the below code will add your desired json to the r:searchData node:
var arr = JArray.Parse(json); // the json string
var payloadNode = arr[0]["data"]["payload"];
// use linq-to-json to create the correct object
var objectToAdd = new JObject(
new JProperty("r:Porelation",
new JObject(
new JProperty("r:ClassA", array1),
new JProperty("r:ClassB", array2))));
payloadNode["r:searchData"] = objectToAdd;
where array1 and array2 above could come from a linq query (or just standard arrays).
// Output:
{
"data": {
"_hash": null,
"kind": "ENY",
"id": "t123",
"payload": {
"r:attributes": {
"lok:934": "#0|I"
},
"r:relations": {
"lok:1445": "15318",
"lok:8538": "08562"
},
"r:searchData": {
"r:Porelation": {
"r:ClassA": [
"P123",
"P456"
],
"r:ClassB": [
"Ba123",
"Ba456"
]
}
},
"r:type": [
"5085"
]
},
"type": "EQT",
"version": "d06"
}
}
Online demo
Another option is to create the json from an object, which could be achieved using JToken.FromObject(). However, this will only work if you have property names which are also valid for C# properties. So, this won't work for your desired property names as they contain invalid characters for C# properties, but it might help someone else:
// create JToken with required data using anonymous type
var porelation = JToken.FromObject(new
{
ClassA = new[] { "P123", "P456" }, // replace with your arrays here
ClassB = new[] { "Ba123", "Ba456" } // and here
});
// create JObject and add to original array
var newObjectToAdd = new JObject(new JProperty("r:Porelation", porelation));
payloadNode["r:searchData"] = newObjectToAdd;
I have this JSON that's a list of objects, like this.
"Fields": [
{
"fieldID": 1,
"name": "field"
}
]
When the list is empty, it is sent like this
"Fields": [
{}
]
I read this in as a string and then try to deserialize it using JsonConvert.DeserializeObject<List<T>>(json); where T is the object that matches the field model. When I do this though, I get a new list with one item in it (count = 1 when it should be 0), the same as if I deserialized this JSON.
"Fields": [
{
"fieldID": 0,
"name": null
}
]
How can I avoid or work around this?
First following json does not represent empty list:
"Fields": [
{}
]
An empty list in json should look like following:
"Fields": []
So you should try to fix the json. However, if that's proven to be impossible you can do something like following:
using (JsonDocument document = JsonDocument.Parse(jsonString))
{
JsonElement root = document.RootElement;
var l = root.EnumerateArray().First().ToString();
if(l=="{}")
{
//do something
}
}
What's happening is that you simply parsing the json and enumerate through the list of element and detect if "{}" exists.
Or, you can go with a more complex way which is writing a custom converter which handles such case in the way you want. You can check out the documentation here
What has been done so far?
I am working on dividing up the number of records into 3 batches and processing them in parallel to increase the performance. However, after processing the batches in parallel I would also like to save the outcome (JSON string) of the processed records in a variable.
As you can see below, I first initialize the variable as List of string and then run the foreach loop which saves the processed outcome as mentioned below.
List<string> responseOutcome = new List<string>();
Parallel.ForEach(recordBatches, batch => {
responseOutcome.Add(response1.Content);
});
Result in List responseOutcome comes as:
responseOutcome[0]
[
{
"Name": "Sample1",
"ID": "123"
},
{
"Name": "Sample2",
"ID": "394"
}
],
responseOutcome[1]
[
{
"Name": "Sample5",
"ID": "384"
},
{
"Name": "Sample6",
"ID": "495"
}
],
responseOutcome[2]
[
{
"Name": "Sample3",
"ID": "473"
},
{
"Name": "Sample4",
"ID": "264"
}
]
What I would like to achieve?
Now I would like to take the value of responseOutcome which is multiple arrays of JSON string and merge them into one big JSON string.
Final Output
[
{
"Name": "Sample1",
"ID": "123"
},
{
"Name": "Sample2",
"ID": "394"
},
{
"Name": "Sample5",
"ID": "384"
},
{
"Name": "Sample6",
"ID": "495"
},
{
"Name": "Sample3",
"ID": "473"
},
{
"Name": "Sample4",
"ID": "264"
}
]
I looked into several similar cases but they weren't nearly similar. Like:
How do I merge multiple json objects
How do I combine two arrays from two JObjects in Newtonsoft JSON.Net?
Any help/guidance will be great!!
Using Newtonsoft, you can create a JArray from each of your responses. Then you can flatten the hierarchy using linq's SelectMany method and re-serialize the object.
Try this:
var obj = responses.Select(r => JArray.Parse(r.Trim(','))).SelectMany(token => token);
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
There are probably more efficient ways to do this if you want to do pure string manipulation, but using Newtonsoft, I would deserialize, merge and then re-serialize.
Create a small POCO model:
public class ResponseOutcomeModel
{
public string ID { get; set; }
public string Name { get; set; }
}
Then deserialize to this model, merge and reserialize to JSON as a single list.
var outcomeList = new List<ResponseOutcomeModel>();
foreach (var i in responseOutcome)
{
outcomeList.AddRange(JsonConvert.DeserializeObject<List<ResponseOutcomeModel>>(i.Trim().TrimEnd(',')));
}
var finalJson = JsonConvert.SerializeObject(outcomeList);
Note, the Time/TrimEnd is used if the trailing commas in your example are really there in your responseOutcome array (at the end of each element in the array). The call to DeserializeObject will complain if you leave the commas in there.
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
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>;