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
Write a Java application that accepts a bar code as a command line parameter and prints...
Write a Java application that accepts a bar code as a command line parameter and prints out the ZIP code. Assume that the bar code uses the symbols "|" and ":" for the long and short bars, respectively. Provide warnings on errors in the bar code specifying what exactly is wrong. The bar code input should be in the format specified in Problem 1, including the pair of the full bars at the beginning and at the end. Important: The...
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 a c# console application app that reads all the services in the task manager and...
write a c# console application app that reads all the services in the task manager and automatically saves what was read in a Notepad txt file.  Please make sure that this program runs, also add some comments
Loops Write a simple C/C++ console application that will calculate the equivalent series or parallel resistance....
Loops Write a simple C/C++ console application that will calculate the equivalent series or parallel resistance. Upon execution the program will request ether 1 Series or 2 Parallel then the number of resisters. The program will then request each resistor value. Upon entering the last resistor the program will print out the equivalent resistance. The program will ask if another run is requested otherwise it will exit.
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; }
Need C++ code for following with a document describing the code as well: Write a program...
Need C++ code for following with a document describing the code as well: Write a program to implement the game of Tic Tac Toe Four. The game is played on a 4 × 4 chessboard, within 2 players. The player who is playing "X" always goes first. Players alternate placing Xs and Os on the board until either one player has four in a row, horizontally, vertically, or diagonally; or all 16 squares are filled(which is a draw). The program...
I need to convert the following into C++. The general idea is to create an application...
I need to convert the following into C++. The general idea is to create an application that can support 10 ID's and 10 grades. It needs to calculate the grade average of said ID, and determine if it is an below or above a certain average, ergo A or C. string[10] studentIDArray int[10] gradeArray int averageGrade for(int i = 0; i < gradeArray; i++) { averageGrade += gradeArray[i] } averageGrade = averageGrade / sizeof(gradeArray) for(int i = 0; i <...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT