Using JSON.Stringify I pass the following string inside another Stringify object.
[
[
"I-000-4310-000",
"Convention Registration",
"59.99"
],
[
"I-000-4311-000",
"Convention Breakout",
"39.99"
]
]
In my C# web service I need to split the string apart into a string array that looks like this:
string[, ,] GLCodes = new string[,,]
{
{
{ "I-000-4310-000", "Convention Registration", "59.99" },
{ "I-000-4311-000", "Convention Breakout", "9.99" }
}
};
What is the simplest way to do this?
Using Json.NET you can deserialize that list with this
string[][] strings = JsonConvert.DeserializeObject<string[][]>(jsonData);
Hope this helps!
Related
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.
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;
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.
I need to access the body of a JSON Code with C#. Accessing the header works but it does not work with the body and I could not find anything in the web.
I have this JSON Code
`{
"Example": {
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
},
......`
However I can acess the headers with following code:
JArray headers = locationsObject["Header"] as JArray;
JArray header = headers.Last as JArray; //Last Header
If I do the same with the body it is null:
JArray bodys = locationsObject["Body"] as JArray; //all bodys -> it works here
JArray body = bodys.First as JArray; //First body -> this one is null!!!
I need the integers in the body. I am using Newtonsoft for that. Can someone help me please? Thank you very much!
your first body is not a JArray that could be the source of the problem, it is rather a JObject, you can try the following code, it should work fine
var bodys = locationsObject["Body"] as JArray;
var body = bodys[0];
you can use also linq-to-json for more fine-tuned operations.
I recommend you to look at serializing/deserializing json in c#.
How to serialize and deserialize (marshal and unmarshal) JSON in .NET
If you do not have a class representation of the json json to c#
Your main line of code will be something like this:
exObj = JsonSerializer.Deserialize<ExampleObject>(jsonString);
And it will be:
string header1 = exObj.Body.Header1;
One way of doing this is by using the 'dynamic' variable type of C# which was specifically designed for functional programming languages. It is not type safe and not strong typed but you can access all the values in the result.
I would however strongly recommend you create classes that mimic the json you are trying to deserialize for it will give you strong typing and intellisense.
Here's an example how you can use dynamic. You need to install the NewtonSoft.Json Nuget package for this to function correctly.
using Newtonsoft.Json;
using System;
namespace JsonDeserialized
{
class Program
{
static void Main(string[] args)
{
string json = #"{
'Example':
{ 'Header':
[
[
'Header1',
'Header2',
'Header3',
'Header4'
]
],
'Body':
[
{
'Header1': 'BlaBla',
'Header2': 0,
'Header3': 20,
'Header4': 32
},
{
'Header1': 'BlaBlaBla',
'Header2': 22,
'Header3': 35,
'Header4': 25
}
]
}
}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(result.Example);
foreach (var header in result.Example.Header[0])
{
Console.WriteLine(header);
}
Console.WriteLine(result.Example.Header[0][0]);
}
}
}
This program will print the following result.
{
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
}
]
}
Header1
Header2
Header3
Header4
Header1
Lets say I get the following json data from a web service which I can't change.
[
[
"Header1",
"Header2",
"Header3",
"Header4"
],
[
"FirstValue1",
"FirstValue2",
"FirstValue3",
"FirstValue4"
],
[
"SecondValue1",
"SecondValue2",
"SecondValue3",
"SecondValue4"
]
]
jsonlint.com tells me that it is valid json and from what I know I would agree.
But somehow I'm wondering is there any "easy" way to deserialize this to a class. Each of the values in the second and third array belongs to the corresponding header in the first array.
I know how to use Json.NET but can't get my head around on how to use it with this data structure.
Simple - you can use JsonConvert.DeserializeObject to deserialize it to a string[][]:
using System;
using System.IO;
using Newtonsoft.Json;
class Test
{
static void Main()
{
var json = File.ReadAllText("test.json");
string[][] array = JsonConvert.DeserializeObject<string[][]>(json);
Console.WriteLine(array[1][3]); // FirstValue4
}
}
The easiest way is to use the string class and deserialzie it using Json.NET.
string[][] values = JsonConvert.DeserializeObject<string[][]>(json);
A better option could be to use
using Newtonsoft.Json.Linq
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
string CPU = o.CPU;
int NumDrives = o.Drives.Count;
Source: http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm