StealthRT
StealthRT

Reputation: 10552

JSON.net combine 2 list(Of JObject) together

Heyy all I am trying to combine 2 JObject lists. I have 2 list(Of JObject) named masterJsonList.Add(jsonWriter.Token) and masterJsonListNA.Add(jsonWriter.Token).

I have not found anything when searching Google that shows me how to combine JObects masterJsonListNA to masterJsonList.

When I try:

masterJsonList.Add(masterJsonListNA) '<-- error here
Dim finalJson As String = JsonConvert.SerializeObject(masterJsonList, Formatting.Indented)

It gives an error of:

Error BC30311 Value of type 'List(Of JObject)' cannot be converted to 'JObject'.

I have even tried the following with no luck as well:

masterJsonList.Concat(masterJsonListNA)
Dim finalJson As String = JsonConvert.SerializeObject(masterJsonList, Formatting.Indented)

Although there is no error using Concat, I only get the masterJsonList values in finalJson and not both masterJsonList & masterJsonListNA.

masterJsonList.Union(masterJsonListNA)
Dim finalJson As String = JsonConvert.SerializeObject(masterJsonList, Formatting.Indented)

And again using Union there is no error, but I also again only get the masterJsonList values in finalJson and not both masterJsonList & masterJsonListNA.

I know it works if I do this:

Dim combinedJsons As Object = masterJsonList.Concat(masterJsonListNA)
Dim finalJson As String = JsonConvert.SerializeObject(combinedJsons, Formatting.Indented)

But I would like to know if that's the correct way of doing this?

Upvotes: 0

Views: 303

Answers (1)

Bozhidar Stoyneff
Bozhidar Stoyneff

Reputation: 3634

Yes. Your final guess is correct. The extension methods Concat, Union, etc. don't operate on the object they're invoked on. Instead they return new object containing the result of the operation. You actually don't need to us As clause for the combinedList - let the compiler to infer it, like so:

Dim combinedJsons = masterJsonList.Concat(masterJsonListNA)

But if you don't need the combinedJsons for anything else you can Concat the lists in place of the first parameter to SerializeObject:

Dim finalJson = JsonConvert.SerializeObject(masterJsonList.Concat(masterJsonListNA), Formatting.Indented)

On the other hand, the List<T>.Add() method do work on the instance it is invoked on, BUT it adds objects of type T, not whole lists of type T.

Upvotes: 1

Related Questions