Question

In: Computer Science

C# I need working code please Write a console application that accepts the following JSON as...

C#

I need working code please

Write a console application that accepts the following JSON as input:

{"menu": {
    "header": "SVG Viewer",
    "items": [
        {"id": "Open"},
        {"id": "OpenNew", "label": "Open New"},
        null,
        {"id": "ZoomIn", "label": "Zoom In"},
        {"id": "ZoomOut", "label": "Zoom Out"},
        {"id": "OriginalView", "label": "Original View"},
        null,
        {"id": "Quality"},
        {"id": "Pause"},
        {"id": "Mute"},
        null,
        {"id": "Find", "label": "Find..."},
        {"id": "FindAgain", "label": "Find Again"},
        {"id": "Copy"},
        {"id": "CopyAgain", "label": "Copy Again"},
        {"id": "CopySVG", "label": "Copy SVG"},
        {"id": "ViewSVG", "label": "View SVG"},
        {"id": "ViewSource", "label": "View Source"},
        {"id": "SaveAs", "label": "Save As"},
        null,
        {"id": "Help"},
        {"id": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}

Then deserialize it, convert it to XML, and print out the result. It should look like the following:

<menu>
    <header>Adobe SVG Viewer</header>
    <item action="Open" id="Open">Open</item>
    <item action="OpenNew" id="OpenNew">Open New</item>
    <separator/>
    <item action="ZoomIn" id="ZoomIn">Zoom In</item>
    <item action="ZoomOut" id="ZoomOut">Zoom Out</item>
    <item action="OriginalView" id="OriginalView">Original View</item>
    <separator/>
    <item action="Quality" id="Quality">Quality</item>
    <item action="Pause" id="Pause">Pause</item>
    <item action="Mute" id="Mute">Mute</item>
    <separator/>
    <item action="Find" id="Find">Find...</item>
    <item action="FindAgain" id="FindAgain">Find Again</item>
    <item action="Copy" id="Copy">Copy</item>
    <item action="CopyAgain" id="CopyAgain">Copy Again</item>
    <item action="CopySVG" id="CopySVG">Copy SVG</item>
    <item action="ViewSVG" id="ViewSVG">View SVG</item>
    <item action="ViewSource" id="ViewSource">View Source</item>
    <item action="SaveAs" id="SaveAs">Save As</item>
    <separator/>
    <item action="Help" id="Help">Help</item>
    <item action="About" id="About">About Adobe CVG Viewer...</item>
</menu>

Solutions

Expert Solution

The program is given below. The comments are provided for the better understanding of the logic. Please note that for parsing, Newtonsoft.Json is used and it has to be installed from Nuget Manager for this solution to work, in the Visual Studio. It is also assumed that the input comes from the command line as the 1st argument. If there is any other mechanism of providing input, the statement "string jsonInput = args[0];" need to be altered. Also since the json input string is multiline and it has double quotes within it, it has to be formatted before passing it to the program (applicable only if it is passing from the command line).

using System;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;

public class JSONHandler
{
    public static void Main(string[] args)
    {
        //Pass the json as the 1st parameter from the command line.
        string jsonInput = args[0];

        //Initialise Newtonsoft JSON Converter
        //This requires Newtonsoft.Json package to be installed from the Nuget Manager
        dynamic parsedJsonObject = JsonConvert.DeserializeObject(jsonInput);

        //The string xmlFormattedString will hold the result xml
        string xmlFormattedString = "<menu>\n";
        //Parse the header and store it.
        xmlFormattedString = xmlFormattedString + String.Format("\t<header>{0}</header>\n", parsedJsonObject.menu["header"]);
        
        ///Loop through the items.
        foreach (Newtonsoft.Json.Linq.JObject items in parsedJsonObject.menu["items"])
        {
            string id = "";
            string label = "";

            //If items is null, it doesn't have any entry and a separator tag need to be inserted in the xml.
            //and continue with the next iteration of the loop.
            if (items is null)
            {
                xmlFormattedString = xmlFormattedString + "\t<separator/>\n";
            }
            else if (items.HasValues)
            {
                if(items.Count == 1)
                {
                    //Check if the sub items are 1.  If so, only id exists and use that as id and label.
                    id = items["id"].ToString();
                    label = items["id"].ToString();
                }
                else
                {
                    //If more than 1 sub items are present, id and label exists and extract that.
                    id = items["id"].ToString();
                    label = items["label"].ToString();
                }
                //format the xml using id and label.
                xmlFormattedString = xmlFormattedString + String.Format("\t<item action=\"{0}\" id=\"{0}\">{1}</item>\n", id, label);
            }
        }
        xmlFormattedString = xmlFormattedString + "</menu>";

        //Print the formatted xml.
        Console.WriteLine(xmlFormattedString);

        Console.ReadLine();
    }
}

The screenshots of the code is provided below.

The input has to be supplied to the program as below. Go to the Project Properties for setting this.

"{'menu': {
    'header': 'SVG Viewer',
    'items': [
        {'id': 'Open'},
        {'id': 'OpenNew', 'label': 'Open New'},
        null,
        {'id': 'ZoomIn', 'label': 'Zoom In'},
        {'id': 'ZoomOut', 'label': 'Zoom Out'},
        {'id': 'OriginalView', 'label': 'Original View'},
        null,
        {'id': 'Quality'},
        {'id': 'Pause'},
        {'id': 'Mute'},
        null,
        {'id': 'Find', 'label': 'Find...'},
        {'id': 'FindAgain', 'label': 'Find Again'},
        {'id': 'Copy'},
        {'id': 'CopyAgain', 'label': 'Copy Again'},
        {'id': 'CopySVG', 'label': 'Copy SVG'},
        {'id': 'ViewSVG', 'label': 'View SVG'},
        {'id': 'ViewSource', 'label': 'View Source'},
        {'id': 'SaveAs', 'label': 'Save As'},
        null,
        {'id': 'Help'},
        {'id': 'About', 'label': 'About Adobe CVG Viewer...'}
    ]
}}"

The output screenshot is provided below.

The Nuget package can be installed as follows.


Related Solutions

I need the code for following in C++ working for Visual studio please. Thanks Use a...
I need the code for following in C++ working for Visual studio please. Thanks Use a Struct to create a structure for a Player. The Player will have the following data that it needs maintain: Struct Player int health int level string playerName double gameComplete bool isGodMode Create the 2 functions that will do the following: 1) initialize(string aPlayerName) which takes in a playername string and creates a Player struct health= 100 level= 1 playerName = aPlayerName gameComplete = 0...
Write a javascript code to replace the JSON body with another JSON body. JSON body1 {...
Write a javascript code to replace the JSON body with another JSON body. JSON body1 {     "name":"john doe",     "mood":"happy"     "major":"cs",     "date":"2024" } json body2 is { "mood":"sad"     "major":"accounting",     "date":"2023" } the result should be { "name":"john doe", "mood":"sad"     "major":"accounting",     "date":"2023" }
I need a working MATLAB CODE for the Gram Schimdt process Please give the code fast...
I need a working MATLAB CODE for the Gram Schimdt process Please give the code fast Its urgent The code must run on any matrix given It should be a generic code Dont answer any wrong code or else i will badly dislike
i need to post a file to a url. The "Content-Type: multipart/form-data" and it "accept: application/json"...
i need to post a file to a url. The "Content-Type: multipart/form-data" and it "accept: application/json" i need to upload a file, three strings. It needs to be in Java, but i keep getting issues.
Write MIPS assembly code for the following C code. for (i = 10; i < 30;...
Write MIPS assembly code for the following C code. for (i = 10; i < 30; i ++) { if ((ar[i] > b) || (ar[i] <= c)) ar[i] = 0; else ar[i] = a; }
You've been hired by Yogurt Yummies to write a C++ console application that calculates and displays...
You've been hired by Yogurt Yummies to write a C++ console application that calculates and displays the cost of a customer’s yogurt purchase. Use a validation loop to prompt for and get from the user the number of yogurts purchased in the range 1-9. Then use a validation loop to prompt for and get from the user the coupon discount in the range 0-20%. Calculate the following:         ● Subtotal using a cost of $3.50 per yogurt.         ● Subtotal...
You've been hired by Avuncular Addresses to write a C++ console application that analyzes and checks...
You've been hired by Avuncular Addresses to write a C++ console application that analyzes and checks a postal address. Prompt for and get from the user an address. Use function getline so that the address can contain spaces. Loop through the address and count the following types of characters:         ● Digits (0-9)         ● Alphabetic (A-Z, a-z)         ● Other Use function length to control the loop. Use functions isdigit and isalpha to determine the character types. Use formatted...
c# code working but output not right, I need to output all numbers like : Prime...
c# code working but output not right, I need to output all numbers like : Prime factors of 4 are: 2 x 2 here is just 2 Prime factors of 7 are: 7 Prime factors of 30 are: 2 x 3 x 5 Prime factors of 40 are: 2 x 2 x 2 x 5 here is just 2,5 Prime factors of 50 are: 2 x 5 x 5 here is just 2,5 1) How I can fix it 2)I...
this is a python code that i need to covert to C++ code...is this possible? if...
this is a python code that i need to covert to C++ code...is this possible? if so, can you please convert this pythin code to C++? def main(): endProgram = 'no' print while endProgram == 'no': print # declare variables notGreenCost = [0] * 12 goneGreenCost = [0] * 12 savings = [0] * 12 months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] getNotGreen(notGreenCost, months) getGoneGreen(goneGreenCost, months) energySaved(notGreenCost, goneGreenCost, savings) displayInfo(notGreenCost, goneGreenCost, savings, months)...
Write a C++ console application to simulate a guessing game. Generate a random integer between one...
Write a C++ console application to simulate a guessing game. Generate a random integer between one and 100 inclusive. Ask the user to guess the number. If the user’s number is lower than the random number, let the user know. If the number is higher, indicate that to the user. Prompt the user to enter another number. The game will continue until the user can find out what the random number is. Once the number is guessed correctly, display a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT