英文:
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 );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论