1

Input JSON:

{
    "name" : "objname",
    "abc" : 1,
    "def" : 2
}

Desired output JSON:

{
    "objname" :
    {
        "abc" : 1,
        "def" : 2 
    }
}

I tried as shown below, but I feel it's not the correct way.

// This is the class object
public class Obj
{
    public string Name { get;set;}
    public string abc { get; set; }
    public string def { get; set; }
}         

var obj = JsonConvert.DeserializeObject<Obj>(json);

StringBuilder sb = new StringBuilder();
sb.Append(" { ");
sb.AppendLine(obj.Name);
sb.AppendLine(" :  {");
sb.AppendLine(GetMemberName(() => obj.abc) + ":" + obj.abc + ",");
sb.AppendLine(GetMemberName(() => obj.def) + ":" + obj.abc);
sb.AppendLine(" :  }");
12
  • input is invalid json and so is the output Commented Jul 22, 2017 at 5:49
  • 2
    1) Your desired output "objname" : { "abc" : 1, "def" : 2 } isn't even JSON, it's missing the outer { and }. 2) What have you tried so far? Commented Jul 22, 2017 at 5:49
  • Look at the homepage for this package. newtonsoft.com/json. You will see a Serialize and DeserializeObject. That's what you need. And please try before asking here. Commented Jul 22, 2017 at 5:50
  • 1
    So please show what you have tried, and what happened. Commented Jul 22, 2017 at 7:14
  • 2
    @GarrGodfrey: No, JSON doesn't have to start with { or [. It's perfectly valid to have a JSON document which is just a string, null token or number for example. But yes, for an object, you do need the braces. Commented Jul 22, 2017 at 7:15

1 Answer 1

2

The first step is deserializing. You can just go to a dictionary:

Dictionary<string, string> dict = 
    JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Then, to get it back, you probably need to use a dictionary as well. You cannot use a predefined (even compiler generated) class, since you don't know the property name.

String name = (string)dict["name"];
// remove name from dictionary
dict.Remove(name);
var output = 
   new Dictionary<string,object>() {{name, dict}};

Then, save it back out:

string json = JsonConvert.SerializeObject(output);
Sign up to request clarification or add additional context in comments.

5 Comments

That will not produce the requested output => .net fiddle
You will have to deserialize to a Dictionary<string,object> instead => .net fiddle
yep, typo. fixing
yeah, saw your fiddle. I was intended as a guide, not ready to go
@GarrGodfrey Thanks a lot. Its working. I was not knowing how to leverage dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.