【问题标题】:Change the values & Type of the JSON data of particular fields更改特定字段的 JSON 数据的值和类型
【发布时间】:2020-08-06 18:33:55
【问题描述】:

用于持久性的 POJO 类

class Target{
private Integer status;
private Integer autoLink;
// other fields

}

输入Json格式

Target
{
"status":"Executed",
"autoLinkIndicator":"YES"
//other fields
}

在持久化之前如何解析JSON并更改字段的值?

例如:

如果我看到“状态”:“已执行”,

我想把它改成“状态”:1 和“状态”:“终止”->“状态”:0

同样,对于“autoLinkIndicator”

1 表示“是”,0 表示“否”

目前, 使用 gson 将 json 解析为 Target 类。

【问题讨论】:

  • 我认为您应该将类​​型保留为 String 并在必要时在解析后应用逻辑。

标签: java json gson json-deserialization


【解决方案1】:

我希望下面的帮助 - 没有类的简单解析器,您可以编辑值并传递给持久层

import java.io.FileReader; 
import java.util.Iterator; 
import java.util.Map; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.*; 

public class JSONReadExample  
{ 
    public static void main(String[] args) throws Exception  
    { 

        Object obj = new JSONParser().parse(new FileReader(<<<<Ur JSON>>>>));
        // typecasting obj to JSONObject 
        JSONObject jsonObj = (JSONObject) obj; 
        // getting status and autoLinkIndicator
        String status = (String) jo.get("status"); 
        String autoLinkIndicator  = (String) jo.get("autoLinkIndicator");        
        System.out.println(status);; 
        System.out.println(autoLinkIndicator); 

    //Code logic to alter the values and then persist
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2018-05-25
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多