How to merge/combine 2 json arrays - c#

So I have 2 json arrays as string in the below variables. They both have the header "invoices" and I would like to merge the two together so there is only 1 header and 4 items inside.
currently have:
var info1 = {"invoices":[{"url":"https://api.freeagent.com/v2/invoices/1","contact":"https://api.freeagent.com/v2/contacts/1"},{"url":"https://api.freeagent.com/v2/invoices/2","contact":"https://api.freeagent.com/v2/contacts/2"}]}
var info2 = {"invoices":[{"url":"https://api.freeagent.com/v2/invoices/3","contact":"https://api.freeagent.com/v2/contacts/3"},{"url":"https://api.freeagent.com/v2/invoices/4","contact":"https://api.freeagent.com/v2/contacts/4"}]}
Desired outcome:
var info3 = {"invoices":[{"url":"https://api.freeagent.com/v2/invoices/1","contact":"https://api.freeagent.com/v2/contacts/1"},{"url":"https://api.freeagent.com/v2/invoices/2","contact":"https://api.freeagent.com/v2/contacts/2"},{"url":"https://api.freeagent.com/v2/invoices/3","contact":"https://api.freeagent.com/v2/contacts/3"},{"url":"https://api.freeagent.com/v2/invoices/4","contact":"https://api.freeagent.com/v2/contacts/4"}]}
Is there any functions that I can use to do this?

The easiest way would be to deserialize them to 2 instances of the same class, add the array items together, and then serialize the object back to string.
Info info1 = // deserialize info1
Info info2 = // deserialize info2
info1.Invoices.AddRange(info2.Invoices);
string json = // serialize info1
Types:
class Info
{
List<Invoice> Invoices;
}
class Invoice
{
string URL;
string Contact;
}

Related

How to get all objects inside an array JSON in a C# controller

How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?
I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....
In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
var obj = JObject.Parse(result);
//Order Info
string invoiceNumber = (string)obj["invoiceNumber"];
string email = (string)obj["email"];
string paymentMethod = (string)obj["paymentMethod"];
string shippingMethod = (string)obj["shippingMethod"];
//Discount info
string amountSaved = (string)obj["discounts"][0]["amountSaved"];
string promoCode = (string)obj["discounts"][0]["code"];
But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.
string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2
How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.
Any suggestions on how I can get this done?
the simpliest way
List<string> names = obj["items"].Select(x => (string) x["name"] ).ToList();
test
Console.WriteLine( string.Join(",",names)); // prod1,prod2
more complicated way is to create a c# class and deserialize data. But in this case you will be able to use Linq for queries and search
List<Item> items = obj["items"].Select(x => x.ToObject<Item>()).ToList()
public class Item
{
public string name { get; set; }
public double price { get; set; }
public int quantity { get; set; }
}
result (in json format)
[
{
"name": "prod1",
"price": 12.99,
"quantity": 4
},
{
"name": "prod2",
"price": 17.65,
"quantity": 1
}
]
You can use Newtonsoft json package to convert an object into JSON array.
Refer below link
http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

Parsing JSON response from StreamBuilder C#

I'm getting a JSON response back from another website and then building the response from a StreamReader:-
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
The result I'm getting is:-
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
I've then used the JsonConvert.DeserializeObject(response) to deserialise and then I'm then trying to loop through the results to read the values.. but it's not working whatever I try
dynamic jObj = JsonConvert.DeserializeObject(response);
var arr = jObj; //Tried var arr = jObj.d;
#foreach (var item in arr)
{
….
}
Error: Target type System.Collections.IEnumerable is not a value type or a non-abstract class.
Parameter name: targetType
Your JSON response contains a d property, which value is an array wrapped into string itself.
So, you should parse a d content separately into array, Json.Linq solution is below
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
var json = JObject.Parse(response);
var array = json["d"];
foreach (var item in JArray.Parse(array.ToString()))
{
Console.WriteLine(item["Animal"]);
}
Solution with deserialization to dynamic object
dynamic json = JsonConvert.DeserializeObject(response);
var array = json?.d;
foreach (var item in JsonConvert.DeserializeObject(array?.ToString()))
{
Console.WriteLine(item?.Animal);
}
It allows you to parse the response without any changes to source JSON
If you printed response, you would see that jObj.d is not an array, but a string. In fact, it looks like the string representation of an array of objects.
It seems that the "d"'s value contains another JSON data. If it is correct and you don't want to touch the JSON format, here is the solution:
string response = "{\"d\":\"[{\\\"Animal\\\":\\\"Cat\\\",\\\"Noise\\\":\\\"Meow\\\"},{\\\"Animal\\\":\\\"Dog\\\",\\\"Noise\\\":\\\"Woof\\\"}]\"}";
dynamic jObj = JsonConvert.DeserializeObject(response);
var arr = JsonConvert.DeserializeObject<D[]>((jObj.d).Value);
foreach (var item in arr)
{
}
........
public class D
{
public string Animal { get; set; }
public string Noise { get; set; }
}

Displaying the name of each object

I'm creating software where the users can create and load profiles to fill textboxes. The names and other information contained in the profile are stored in a JSON file. A profile name can contain any text that is entered by the user.
So for this, I'm trying to get each objects names of the JSON file (= each profile name) to display them in a treeview, but all I get is their contents.
I have a JSON file containing two objects:
[
{
"profile1": {
//Some informations 1
},
"profile2": {
//Some informations 2
}
}
]
For now, I have code that allows me to get the value of a given tag, but I can't find a way to get the name of each objects:
using (StreamReader r = File.OpenText(path))
{
string json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
debug_tb.Text += item.profile1; //Gives me each values of the "profile1 object"
}
}
So what I'm trying to get is to display "profile1" and "profile2" and "profile3" if it exists.
Your problem is that your JSON is an array with one object. So you can simplefy the JSON first:
{
"profile1": {
//Some informations 1
},
"profile2": {
//Some informations 2
}
}
Then you can easyly iterate over every item in the JSON and get the Name of it
dynamic array = JsonConvert.DeserializeObject("{ \"profile1\": { }, \"profile2\": { } }");
foreach (var item in array)
{
debug_tb.Text += item.Name; //Gives the name of the object
}
Console.WriteLine(text);
Console.ReadLine();

set props value from text field, and convert it into a list of JSON objects and store in a file

I am trying to get data from web form and convert properties into a list of json objects through json.net, first time a list of object is stored in a file. But next time, instead of appending data into list it creates new list. So how can I add it in same list. Here is my code
public List<StudentProps> GetProps(StudentProps p)
{
List<StudentProps> s = new List<StudentProps>();
s.Add(p);
return s;
}
public void GetStudent(StudentProps p)
{
var json = JsonConvert.SerializeObject(GetProps(p), Formatting.Indented);
String FilePath = #"C:\Users\Haseeb\Desktop\Test.json";
File.AppendAllText(FilePath, json + Environment.NewLine);
var ReadFile = File.ReadAllText(FilePath);
// List<StudentProps> props = JsonConvert.DeserializeObject<List<StudentProps>>(ReadFile).ToList();
}

How to deserialize JSON-Object?

i am trying to deserialize a JSON-Object which looks quite similiar to an Array.
Here's the JSON-String:
...,"Test":[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],...
I do not want to deserialize it as 2D Array, because each of these values have an explicit meaning to me. I would like to access it like this:
Test[0].Example (0)
Test[0].Êxample2 (1)
Test[0].Example3 (2)
...
Test[2].Example (10)
I hope you got the idea and have a solution to my Problem.
I am using the Newtonsoft JSON Library together with C#.
EDIT1:
Maybe i should be more specific of how deserilisation is done until now:
JSON:"Object":{"A":0,"Test":[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],"B":1,...}
C#:
m_Object = JsonConvert.DeserializeObject<Object>(jsonString);
The Class Object is defined in C# containing all the fields of the JSON-String.
Object-Class:
class Object
{
public Int32 A {get;set;}
public Object Test {get;set;}
public Int32 B {get;set;}
}
You can use LINQ to JSON:
string json = "[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]]";
var tests = JsonConvert.DeserializeObject<JArray>(json)
.Cast<JArray>()
.Select(a => new Test {
Example = (int)a[0],
Example2 = (int)a[1]
// etc
});
Result:
UPDATE: For your updated question - you can deserialize json object, and then access its properties by their keys
string json = #"{'A':0,'Test':[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]],'B':1}";
var obj = JsonConvert.DeserializeObject<JObject>(json);
var test = (JArray)obj["Test"];
var result = new {
A = (int)obj["A"],
B = (int)obj["B"],
Test = test.Cast<JArray>().Select(a => new Test {
Example = (int)a[0],
Example2 = (int)a[1],
Example3 = (int)a[2],
Example4 = (int)a[3],
Example5 = (int)a[4]
})
};

Categories

Resources