将 JSON 作为字符串传递

huangapple go评论72阅读模式
英文:

Passing json as a String

问题

对于一个类似以下 JSON 结构的请求体:

{
    "firstName": "hello",
    "lastName": "abc"
}

我可以这样编写:

JSONObject body = new JSONObject();

body.put("firstName", "hello");
body.put("lastName", "abc");

然后将 body 转换为字符串,以便将其作为字符串参数传递。

那么,如果响应的 JSON 结构如下:

{
    "class": {
        "firstName": "hello",
        "lastName": "abc"
    }
}

我需要如何进行相同的处理呢?我需要将 JSON 转换为字符串以便之后传递。

英文:

For a Json body like

{
    "firstName": "hello",
    "lastName": "abc"
}

I am writing as

JSONObject body = new JSONObject();

	
body.put("firstName", "hello");
body.put("lastName", "abc");

and then converting body to string to pass it as string parameter

How can I write the same for body with response like

{
    "class": {
        "firstName": "hello",
        "lastName": "abc"
    }
}

I need to convert json to string afterwards

答案1

得分: 1

我认为这应该会起作用

JSONObject innerBody = new JSONObject();
innerBody.put("firstName", "hello");
innerBody.put("lastName", "abc");

JSONObject outerBody = new JSONObject();
outerBody.put("class", innerBody);

英文:

I think this should do the trick

    JSONObject innerBody = new JSONObject();
    innerBody.put("firstName", "hello");
    innerBody.put("lastName", "abc");

    JSONObject outerBody = new JSONObject();
    outerBody.put("class",innerBody);

答案2

得分: 0

创建一个类:

public class DataSource {
    private String firstName;
    private String lastName;
    // 构造方法,getter 和 setter 方法
}

然后:

JSONObject body = new JSONObject();
DataSource data = new DataSource();
data.setFirstName("bla");
data.setLastName("bla bla");
body.put("class", data);
英文:

Create a class:

public class DataSource {
    private String firstName;
    private String lastName;
    //Constructor, getter, setter
}

And then:

JSONObject body = new JSONObject();
DataSource data = new DataSource();
data.setFirstName("bla");
data.setLastName("bla bla");
body.put("class", data );

huangapple
  • 本文由 发表于 2020年8月28日 14:39:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63628723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定