[{"orgName":"重庆市帆跃加油站有限公司","type":"LEGAL_PERSON","socialCreditCode":"91500116576167022Q","userId":"9926938465029"}]java中如何使用对象接收这个json里的对象
时间: 2024-07-29 20:00:42 浏览: 103
在Java中,你可以使用`Gson`库将JSON字符串转换为对象。如果你有一个包含具体键值对(如`LEGAL_PERSON`和`socialCreditCode`)的JSON字符串,比如:
```json
{
"orgName": "重庆市帆跃加油站有限公司",
"type": "LEGAL_PERSON",
"socialCreditCode": "91500116576167022Q",
"userId": "9926938465029"
}
```
首先,你需要添加Gson依赖到你的项目中。如果你用的是Maven,可以在pom.xml文件里添加:
```xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.x.x</version> <!-- 更新到最新版本 -->
</dependency>
```
然后,你可以创建一个对应的Java类来映射这个JSON结构,假设我们将其命名为`CompanyInfo`:
```java
public class CompanyInfo {
private String orgName;
private String type;
private String socialCreditCode;
private String userId;
// getters and setters
public String getOrgName() { return orgName; }
public void setOrgName(String orgName) { this.orgName = orgName; }
// ... (剩下的字段和getter/setter)
}
```
接下来,你可以使用Gson的`fromJson`方法将JSON字符串转换为`CompanyInfo`对象:
```java
String jsonString = "{\"orgName\":\"重庆市帆跃加油站有限公司\",\"type\":\"LEGAL_PERSON\",\"socialCreditCode\":\"91500116576167022Q\",\"userId\":\"9926938465029\"}";
Gson gson = new Gson();
CompanyInfo companyInfo = gson.fromJson(jsonString, CompanyInfo.class);
```
这样,`companyInfo`对象就包含了从JSON字符串解析出的数据了。
阅读全文
相关推荐


















