2

I am working with a huge JSON file, where is just needed to extract some fields inside it. I've been searching some ways to deserialize, but don't want to create the whole Class and Object in C# with all the fields inside the JSON, this would be a lot of useless memory.

I can get the JSON file using a Webclient:

using (WebClient wc = new WebClient())
{
   jsonWeb = wc.DownloadString("http://link_to_get_JSON");
}

//Deserialize into a JObject
JObject obj = JObject.Parse(jsonWeb);

//Tried to access the info with
var val = obj.PropTwo;
var solution = obj.Descendants().OfType<JProperty>().Where(p => p.Name == "solverSolution").Select(x => x.Value.ToString()).ToArray();

I really could not find a way to get the wanted fields inside the JObject. Inside the JSON, the only information is needed is the solverSolution:{} below:

{
   "content":
   [
      {
         "id":"f4d7e7f5-86ab-4155-8336-ca5f552cb3b4",
         "name":"m1",
         "description":"m1",
         "maxHeight":2000.0,
         "layers":6,
         "pallet":{},
         "product":{},
         "solverSolution":
         {
            "id":"106ef605-d95e-4c74-851b-63310fbcbc7d",
            "name":"solver",
            "maxHeight":2000.0,
            "layers":6,
            "solution":[
            {
               "X1":0,
               "Y1":0,
               "Z1":0,
               "X2":296,
               "Y2":246,
               "Z2":220
            },
            ...
            "default":false
         },
         "customSolutions":[0]
      },
     {},
     ...
   ],
   "pageable":{},
   "totalPages":1,
   "last":true,
   "totalElements":7,
   "first":true,
   "sort":{},
   "number":0,
   "numberOfElements":7,
   "size":20
}

Here I leave my appreciation and gratitude for the community beforehand. Cheers,

André Castro.

  • 3
    http://idownvotedbecau.se/noattempt/ StackOverflow is not a codewriting service. We assist with specific issues. Show us what you've tried and where you need help and we can assist. – gilliduck Sep 21 '18 at 15:00
  • 1
    Show some code of what was tried and is giving problems. We should be able to help from there as currently the question is too broad as there are multiple ways to do this. – Nkosi Sep 21 '18 at 15:03
  • Something with a [`JsonReader`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm) would be the way to go here. – spender Sep 21 '18 at 15:07
  • Just edited with more info about what I tryed. – André Castro Sep 21 '18 at 15:12
  • Without creating an object in c#, you may have to resort to some creative string manipulation. – Mark Schultheiss Sep 21 '18 at 15:22

3 Answers3

5

Then use only the desired properties in your object, making sure to follow the structure of the desired model.

public partial class RootObject {
    [JsonProperty("content")]
    public Content[] Content { get; set; }
}

public partial class Content {
    [JsonProperty("solverSolution")]
    public SolverSolution SolverSolution { get; set; }
}

public partial class SolverSolution {
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("maxHeight")]
    public double MaxHeight { get; set; }

    [JsonProperty("layers")]
    public long Layers { get; set; }

    [JsonProperty("solution")]
    public Solution[] Solution { get; set; }

    [JsonProperty("default")]
    public bool Default { get; set; }
}

public partial class Solution {
    [JsonProperty("X1")]
    public long X1 { get; set; }

    [JsonProperty("Y1")]
    public long Y1 { get; set; }

    [JsonProperty("Z1")]
    public long Z1 { get; set; }

    [JsonProperty("X2")]
    public long X2 { get; set; }

    [JsonProperty("Y2")]
    public long Y2 { get; set; }

    [JsonProperty("Z2")]
    public long Z2 { get; set; }
}

The parser will ignore the rest that do not map to properties of the object model.

var root = Jsonsonvert.DeserializeObject<RootObject>(jsonWeb);
var solverSolution = root.Content[0].SolverSolution;

How can I get all SolverSolution

SolverSolution[] solutions = root.Content.Select(content => content.SolverSolution).ToArray();
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • I will give that a try! Thanks a lot. – André Castro Sep 21 '18 at 15:20
  • To do this yourself with any JSON object...using Visual Studio you can copy and paste your JSON string straight in to C# classes, allowing you to deserialize your string into those classes exactly as shown above. – jcc Sep 21 '18 at 15:22
  • 1
    @jcc agreed, but the OP does not want any of the other properties. I used the same approach you suggested. I just removed the unwanted fields from the JSON and generated the desired classes. – Nkosi Sep 21 '18 at 15:24
  • Hey, @Nkosi. The above code worked. If I want to access the first SolverSolution I can do like this ``var solverSolution = root.Content.First().solverSolution;`` Since the ``Content`` has many ``SolverSolution``s. How can I get them all? ``SolverSolution[] solutions = root.Content...`` – André Castro Sep 21 '18 at 16:32
2

I use:

JsonConvert.DeserializeObject<dynamic>(stringInput)

to get anonymouse type I need

Then you can use something like this to get specific part:

var obj = JsonConvert.DeserializeObject<dynamic>(input)["content"][0]["solverSolution"];

It's easy and gets me job done.

Edit: Side note, please next time when you upload json just cut off parts that are not needed so I can serialize it, took me some time to fix it :D

BitByBit
  • 21
  • 2
  • Hey, @BitByBit. Indeed the answer you provided can be used to get a specific field in the JSON file. However the content in ``var obj`` is still in JSON format. Should I need to create a ``Partial Class`` to acess the information easily? – André Castro Sep 21 '18 at 17:00
  • 1
    var obj is `JObject`, you could use `JObject` as generic parameter, instead of dynamic like I did. And then you can access members of returned instance (obj). I.e obj["id"] would return you id value, 106ef605-d95e-4c74-851b-63310fbcbc7d. It is not json string that is returned, it is just that if you try to Console.WriteLine(obj), you call obj.ToString(), which returns string formatted as json. – BitByBit Sep 21 '18 at 17:19
0

You can use a JObject to parse all Json. Then, you can map a specific children to your object.

Reference

  • 4
    You should show more details in the answer itself as links can go dead. Use the link as reference but put as much detail in the answer a required to solve the problem. – Nkosi Sep 21 '18 at 15:05
  • 2
    How does this tally with the requirement "don't want to create the whole Object in C#"? – spender Sep 21 '18 at 15:05
  • Welcome to StackOverflow. We do appreciate the reference, but a short bit of code showing HOW will improve your answer from a "possible comment" to a proper answer as others have suggested. See examples of highly up voted answers to questions that might also give you ideas on how to also create a great answer from your knowledge. – Mark Schultheiss Sep 21 '18 at 15:31
  • Here is a great answer example from the author of exact reference you cite: https://stackoverflow.com/a/1212115/125981 Note it is fairly short, but does include sample code. Think of great answers as SHOW as well as TELL! – Mark Schultheiss Sep 21 '18 at 15:33