question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Example of using foreach on JSONNode ?

See original GitHub issue

Hello there, I found your very useful SimpleJSON script and I expect it will save me a lot of time. Thank you! I wondered if you could demonstrate how to use it in a foreach and switch statement way. Something like this:

       var UserSettings = JSON.Parse(json_string);

        // Merge UserSettings into DefaultSettings
        foreach ( var rootElement in UserSettings)
        {
            switch (rootElement.Key)
            {
                case "ClockType":
                    AirSimSettings.GetSettings().ClockType = rootElement.Value;
                    break;
                case "ClockSpeed":
                    AirSimSettings.GetSettings().ClockSpeed = rootElement.Value.AsDouble;
                    break;
                case "Recording":
                    foreach (var sub1 in UserSettings["Recording"])
                    {
                        switch (sub1.Key)
                        {
                            case "RecordOnMove":
                                AirSimSettings.GetSettings().Recording.RecordOnMove = sub1.Value.AsBool;
                                break;
                            case "RecordInterval":
                                AirSimSettings.GetSettings().Recording.RecordInterval = sub1.Value.AsDouble;
                                break;
                            case "Cameras":
                                AirSimSettings.GetSettings().Recording.Cameras.Clear();
                                foreach (var sub2 in UserSettings["Recording"]["Cameras"])
                                {
                                    var camsettings = sub2.Value.AsArray;
                                    foreach (var cs in camsettings)
                                    {
                                        AirSimSettings.CamerasSettings NewRecordingCameraSetting = new AirSimSettings.CamerasSettings
                                        {
                                            CameraName = "0",
                                            ImageType = 0,
                                            PixelAsFloat = false,
                                            Compress = true
                                        };
                                        foreach (var cam in cs.Value)
                                        {
                                            switch (cam.Key)
                                            {
                                                case "CameraName":
                                                    NewRecordingCameraSetting.CameraName = cam.Value;
                                                    break;
                                                case "ImageType":
                                                    NewRecordingCameraSetting.ImageType = cam.Value.AsInt;
                                                    break;
                                                case "PixelAsFloat":
                                                    NewRecordingCameraSetting.PixelAsFloat = cam.Value.AsBool;
                                                    break;
                                                case "Compress":
                                                    NewRecordingCameraSetting.Compress = cam.Value.AsBool;
                                                    break;
                                            }
                                        }
                                        AirSimSettings.GetSettings().Recording.Cameras.Add(NewRecordingCameraSetting);
                                    }
                                }
                                break; // Cameras
                        }
                    }
                    break; // Recording
}

Is this the correct way if one wanted to first parse the root elements of the JSON data structure. And then also do subsequent parsing of sub elements? A little example of this would be helpful. 😃

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Bunny83commented, Feb 18, 2019

My bad, it should be either

foreach (JSONNode camNode in recordingNode["Cameras"])

or when you used the orininal code, you would have to use

foreach (var camNode in recordingNode["Cameras"])
{
    CameraName = camNode.Value["CameraName"],

The normal enumerator uses KeyValuePairs. The framework comes with an implicit conversion from KeyValuePair(string, JSONNode) to JSONNode. So when we declare camNode explicitly as JSONNode it will be converted automatically.


However using .Children does work as well. Though the Children enumerator will allocate memory as it’s a classic IEnumerable


The null-coalescing would not work as the framework would return a lazy creator object in case a value doesn’t exist. The lazy creator implements a custom == operator which would return true if compared against null. However the null-coalescing operator does not use the == operator for the null check. It directly compares the reference against null which will never be the case.


I quickly added a “HasKey” and a GetValueOrDefault method to simplify reading conditionally. So you can do something like this:

CameraName = camNode.GetValueOrDefault("CameraName", "defaultName")

Note that the default value is of type JSONNode. Since all supported types are implicitly converted to JSONNode you can directly pass int, string, float, bool, … values. Just keep in mind that the "defaultName" will actually result in new JSONString("defaultName").

1reaction
Bunny83commented, Feb 17, 2019

Note my comment assumed a json file like this:

{
    "ClockType" : "yourClockType",
    "ClockSpeed" : 1.23,
    "Recording" : {
        "RecordOnMove" : true,
        "RecordInterval" : 0.25,
        "Cameras" : [
            {
                "CameraName" : "Cam 1",
                "ImageType" : 2,
                "PixelAsFloat" : false,
                "Compress" : true
            },
            {
                "CameraName" : "Cam 2",
                "ImageType" : 2,
                "PixelAsFloat" : false,
                "Compress" : true
            },
        ]
    }
}

Read more comments on GitHub >

github_iconTop Results From Across the Web

com.fasterxml.jackson.databind.JsonNode.forEach java ...
How to use. forEach. method. in. com.fasterxml.jackson.databind.JsonNode ... textValue(); // Add the method-specific examples. service.get("methods").
Read more >
Jackson JsonNode.forEach() with Java 8 Consumer
forEach () method which will accept Java 8 consumer definition to iterate each node. The consumer accepts only super classes of JsonNode. It...
Read more >
Jackson JsonNode.forEach() with Java 8 Consumer
forEach () method which will accept Java 8 consumer definition to iterate each node. The consumer accepts only super classes of JsonNode. It...
Read more >
Example usage for com.fasterxml.jackson.databind ...
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Read more >
How to iterate all subnodes of a json object?
This will work for you : ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); Map<String, String> map = new ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found