简体   繁体   中英

having difficulties with c# to Json

i am quite new to Json, i have a program which makes a put request with some json data.

i need to make the equivelant of this: { "project": { "date_closed":"2017-01-05"} }

and this is my code i need to adapt..

object instructionData = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") };

var instructionString = JsonConvert.SerializeObject(instructionData);
StringContent instruction = new StringContent(instructionString, Encoding.UTF8, "application/json");

which is currently more than i can seem to figure out...

i've looked at some converters, which just creates classes. And those i don't really know what to do with..

Hope there is someone willing to help.

Edit i am creating a response which is being sent.

var response = instructions.GetPutResponse(instructions.GetCleanUpProjectsRequestUrl(projectId), instructions.GetJsonInstructions(instructionData), client);

GetPutResponse method:

public HttpResponseMessage GetPutResponse(string requestUrl, HttpContent httpContent, HttpClient client)
    {
        return client.PutAsync(requestUrl, httpContent).Result;
    }

Like one of comments above suggests using string concatenation which seems fair approach however if you don't want to go that route then you can use following snippet to achieve what you want. Replace below line

object instructionData = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") };

with

var instructionData = new { projects = new { date_closed = DateTime.Now.ToString("yyyy-MM-dd") } };
public class Project
{
    public string date_closed { get; set;}
}

public class MyClass
{
    public Project project { get; set;}
}

var obj = new MyClass();
obj.project = new Project();
obj.project.date_closed = DateTime.Now.ToString("yyyy-MM-dd");

var instructionString = JsonConvert.SerializeObject(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM