java 获取JSON上的反斜杠

jobtbby3  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(104)

Java POJO类在“数据点”之下是什么?数据点不是常数,它们的值和数量以及计数可以增加或减少。
这下面是我从我的代码中得到的输出,我得到了反斜杠。

[
    {
        "id": "346id71",
        "arg": {
            "test1": "pass",
            "task": "true",
            "direction": "right"
        },
        "datapoints": "{\"1694473620\":0.0008208249347420499,\"1694509620\":0.0008401434897869077,\"1694545620\":0.0008438824499876583,\"1694581620\":0.0008171293069653031,\"1694617620\":0.0008596749524634415,\"1694653620\":0.0008368097665295172}"
    },
    {
        "id": "346id72",
        "arg": {
            "test1": "pass",
            "task": "true",
            "direction": "left"
        },
        "datapoints": "{\"1694473620\":0.0008208249347420499,\"1694509620\":0.0008401434897869077,\"1694545620\":0.0008438824499876583,\"1694581620\":0.0008171293069653031,\"1694617620\":0.0008596749524634415,\"1694653620\":0.0008368097665295172}"
    }
]

这下面是所需的输出,但我得到反斜杠在“数据点”如上所述

[
    {
        "id": "346id71",
        "arg": {
            "test1": "pass",
            "task": "true",
            "direction": "right"
        },
        "datapoints": {
            "1680012000": 0.10124447461480172,
            "1680048000": 8.39834838777665454,
            "1680084000": 8.33850837187659432,
            "1680120000": 8.35752337464636549
            }
    },
    {
        "id": "346id72",
        "arg": {
            "test1": "pass",
            "task": "true",
            "direction": "left"
        },
        "datapoints": {
            "1680012000": 0.123233,
            "1680048000": 3.567384,
            "1680084000": 4.476530,
            "1680120000": 0.0,
            "1680156000": 0.0
          }
    }
]

我尝试了很多,但无法找出适当的解决方案,以消除反斜杠。
这是我的模型课

public class Response {

    private String id;
    private Arg arg;
    private String datapoints;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Arg getArg() {
        return arg;
    }
    public void setArg(Arg arg) {
        this.arg = arg;
    }
    public String getDatapoints() {
        return datapoints;
    }
    public void setDatapoints(String datapoints) {
        this.datapoints = datapoints;
    }
    
    
}

数据点的输入字符串如下所示

{"1694473620":0.0008232249347420499,"1694509620":0.0008405554897869077,"1694545620":0.0008438824476576583,"1694581620":0.0008171293069653031,"1694617620":0.0008596749524634415,"1694653620":0.0008368097665295172}
nmpmafwu

nmpmafwu1#

您应该具有以下结构。我使用Jackson处理反序列化/序列化,使用Lombok处理POJO字段的getters/setters/toString。
正如其他人所提到的,datapoints的类型应该是StringDoubleMap

import java.util.Arrays;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

public class ParseJson {
    private static final String SAMPLE_JSON_DATA = "[{\"id\":\"346id71\",\"arg\":{\"test1\":\"pass\",\"task\":\"true\",\"direction\":\"right\"},\"datapoints\":{\"1680012000\":0.10124447461480172,\"1680048000\":8.398348387776654,\"1680084000\":8.338508371876594,\"1680120000\":8.357523374646366}},{\"id\":\"346id72\",\"arg\":{\"test1\":\"pass\",\"task\":\"true\",\"direction\":\"left\"},\"datapoints\":{\"1680012000\":0.123233,\"1680048000\":3.567384,\"1680084000\":4.47653,\"1680120000\":0,\"1680156000\":0}}]";

    private static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        Response[] response = mapper.readValue(SAMPLE_JSON_DATA, Response[].class);
        System.out.println("\nOUTPUT :- Object::toString");
        System.out.println(Arrays.toString(response));
        System.out.println("\nOUTPUT :- ObjectMapper::writeValueAsString");
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
    }

    @Data
    private static class Arg {
        String test1, task, direction;
    }

    @Data
    private static class Response {
        private String id;
        private Arg arg;
        private Map<String, Double> datapoints;
    }
}

输出

下面是.toString()调用:

[
  ParseJson.Response(
    id=346id71,
    arg=ParseJson.Arg(test1=pass, task=true, direction=right),
    datapoints={
      1680012000=0.10124447461480172,
      1680048000=8.398348387776654,
      1680084000=8.338508371876594,
      1680120000=8.357523374646366}
  ),
  ParseJson.Response(
    id=346id72,
    arg=ParseJson.Arg(test1=pass, task=true, direction=left),
    datapoints={
      1680012000=0.123233,
      1680048000=3.567384,
      1680084000=4.47653,
      1680120000=0.0,
      1680156000=0.0}
  )
]

.writerWithDefaultPrettyPrinter().writeValueAsString()调用:

[ {
  "id" : "346id71",
  "arg" : {
    "test1" : "pass",
    "task" : "true",
    "direction" : "right"
  },
  "datapoints" : {
    "1680012000" : 0.10124447461480172,
    "1680048000" : 8.398348387776654,
    "1680084000" : 8.338508371876594,
    "1680120000" : 8.357523374646366
  }
}, {
  "id" : "346id72",
  "arg" : {
    "test1" : "pass",
    "task" : "true",
    "direction" : "left"
  },
  "datapoints" : {
    "1680012000" : 0.123233,
    "1680048000" : 3.567384,
    "1680084000" : 4.47653,
    "1680120000" : 0.0,
    "1680156000" : 0.0
  }
} ]
txu3uszq

txu3uszq2#

我尝试了很多,但无法找出适当的解决方案,以消除反斜杠。
我认为你可以使用String.replaceAll()方法删除datapoints字段中的反斜杠:

public class Response {

    private String id;
    private Arg arg;
    private String datapoints;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Arg getArg() {
        return arg;
    }

    public void setArg(Arg arg) {
        this.arg = arg;
    }

    public String getDatapoints() {
        return datapoints;
    }

    public void setDatapoints(String datapoints) {
        this.datapoints = datapoints.replaceAll("\\\\", "");
    }
}
u59ebvdq

u59ebvdq3#

我认为你需要联系创建JSON的人,并要求他们重新构造它。也就是说,这里有一种使用GSON解析当前JSON的方法。首先我注意到的是\"都需要是'。从那里,使用TypeAdapter读取JSONDataPointsPOJO在我看来应该是Map。代码中的注解!

主菜单

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
 * @author blj0011 (sedj601)
 */
public class JavaTestArea {
    public static void main(String[] args) {    
        String jsonArrayString = 
                """
                [
                    {
                        "id": "346id71",
                        "arg": {
                            "test1": "pass",
                            "task": "true",
                            "direction": "right"
                        },
                        "datapoints": "{\"1694473620\":0.0008208249347420499,\"1694509620\":0.0008401434897869077,\"1694545620\":0.0008438824499876583,\"1694581620\":0.0008171293069653031,\"1694617620\":0.0008596749524634415,\"1694653620\":0.0008368097665295172}"
                    },
                    {
                        "id": "346id72",
                        "arg": {
                            "test1": "pass",
                            "task": "true",
                            "direction": "left"
                        },
                        "datapoints": "{\"1694473620\":0.0008208249347420499,\"1694509620\":0.0008401434897869077,\"1694545620\":0.0008438824499876583,\"1694581620\":0.0008171293069653031,\"1694617620\":0.0008596749524634415,\"1694653620\":0.0008368097665295172}"
                    }
                ]
                """; 
        
        //This code finds " in datapoints and replaces it with '
        //EX: 
        //This ->    "datapoints": "{\"1694473620\":0.0008208249347420499,\"1694509620\":0.0008401434897869077,\"1694545620\":0.0008438824499876583,\"1694581620\":0.0008171293069653031,\"1694617620\":0.0008596749524634415,\"1694653620\":0.0008368097665295172}"
        //Becomes -> "datapoints": "{'1694473620':0.0008208249347420499,'1694509620':0.0008401434897869077,'1694545620':0.0008438824499876583,'1694581620':0.0008171293069653031,'1694617620':0.0008596749524634415,'1694653620':0.0008368097665295172}"                   
        List<Integer> beginDataPoints = Pattern.compile(Pattern.quote("\"{\"")) // sanitize input and create pattern
            .matcher(jsonArrayString) // create matcher
            .results()     // get the MatchResults, Java 9 method
            .map(MatchResult::start) // get the first index
            .collect(Collectors.toList()); // collect found indices into a list
        
        List<Integer> endDataPoints = Pattern.compile(Pattern.quote("}\"")) // sanitize input and create pattern
            .matcher(jsonArrayString) // create matcher
            .results()     // get the MatchResults, Java 9 method
            .map(MatchResult::start) // get the first index
            .collect(Collectors.toList());
//        
        for( int i = 0; i < beginDataPoints.size(); i++){
            jsonArrayString = jsonArrayString.replace(jsonArrayString.substring(beginDataPoints.get(i) + 2, endDataPoints.get(i) - 1), jsonArrayString.substring(beginDataPoints.get(i) + 2, endDataPoints.get(i) - 1).replace("\"", "'"));
        }        
        
        //This code set up GSON and parse the JSON      
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Response.class, new ResponseTypeAdapter());
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();        
       Response[] responseArray = gson.fromJson(jsonArrayString, Response[].class);
        
       //This code prints the Response array objects!
        for(int i = 0; i < responseArray.length; i++){
            System.out.println(responseArray[i].toString());
        }        
    }    
}

ResponseTypeAdapter

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author blj0011 (sedj601)
 */
public class ResponseTypeAdapter extends TypeAdapter<Response> {

    @Override
    public void write(JsonWriter out, Response value) throws IOException {
        //You do this if needed!
//        out.beginObject();
//        out.name("id").value(value.getId());
//        out.beginObject();
//        out.name("arg").value(value.getArg().getTest1());
//        out.name("dataPoints").value("Todo - datapoints here!");
//        out.endObject();
    }

    @Override
    public Response read(JsonReader in) throws IOException {
        Response response = new Response();
        in.beginObject();
        while (in.hasNext()) {
            // should really handle nulls for the strings...
            switch(in.nextName()) {
                case "id" -> response.setId(in.nextString());
                case "arg" -> {
                    Arg arg = new Arg();
                    in.beginObject();
                    while(in.hasNext()){
                        switch (in.nextName()) {
                            case "test1" -> {
                                arg.setTest1(in.nextString());
                            }
                            case "task" -> {
                                arg.setTask(in.nextString());
                            }
                            case "direction" -> {
                                arg.setDirection(in.nextString());
                            }
                        }
                    }
                    response.setArg(arg);
                    in.endObject();
                }
                case "datapoints" -> {
                    String datapoints = in.nextString();
                    //System.out.println(datapoints);
                    Gson gson = new Gson();
                    Map map = gson.fromJson(datapoints, Map.class);
                    DataPoints dataPointsObject = new DataPoints(map);
                    response.setDataPoints(dataPointsObject);
                }                
            }        
        }
        
        in.endObject();
        return response ;
    }    
}

响应

/**
 *
 * @author blj0011 (sedj601)
 */
public class Response {
    private String id;
    private Arg arg;
    private DataPoints dataPoints;

    public Response(){}
    
    public Response(String id, Arg arg, DataPoints dataPoints) {
        this.id = id;
        this.arg = arg;
        this.dataPoints = dataPoints;
    }

    public DataPoints getDataPoints() {
        return dataPoints;
    }    
    
    public void setDataPoints(DataPoints dataPoints) {
        this.dataPoints = dataPoints;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Arg getArg() {
        return arg;
    }

    public void setArg(Arg arg) {
        this.arg = arg;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Response{");
        sb.append("id=").append(id);
        sb.append(", arg=").append(arg);
        sb.append(", dataPoints=").append(dataPoints);
        sb.append('}');
        return sb.toString();
    }   
}

数据点

import java.util.Map;

/**
 *
 * @author blj0011 (sedj601)
 */
public class DataPoints {
    private Map<String, Double> points;

    public DataPoints(Map<String, Double> points) {
        this.points = points;
    }

    public Map<String, Double> getPoints() {
        return points;
    }

    public void setPoints(Map<String, Double> points) {
        this.points = points;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("DataPoints{");
        sb.append("points=").append(points);
        sb.append('}');
        return sb.toString();
    }    
}

参数

/**
 *
 * @author blj0011(sedj601)
 */
public class Arg {
    private String test1;
    private String task;
    private String direction;

    public Arg(){}
    
    public Arg(String test1, String task, String direction) {
        this.test1 = test1;
        this.task = task;
        this.direction = direction;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public String getTest1() {
        return test1;
    }

    public void setTest1(String test1) {
        this.test1 = test1;
    }

    public String isTask() {
        return task;
    }

    public void setTask(String task) {
        this.task = task;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Arg{");
        sb.append("test1=").append(test1);
        sb.append(", task=").append(task);
        sb.append(", direction=").append(direction);
        sb.append('}');
        return sb.toString();
    }
}

输出

Response{id=346id71, arg=Arg{test1=pass, task=true, direction=right}, dataPoints=DataPoints{points={1694473620=8.208249347420499E-4, 1694509620=8.401434897869077E-4, 1694545620=8.438824499876583E-4, 1694581620=8.171293069653031E-4, 1694617620=8.596749524634415E-4, 1694653620=8.368097665295172E-4}}}
Response{id=346id72, arg=Arg{test1=pass, task=true, direction=left}, dataPoints=DataPoints{points={1694473620=8.208249347420499E-4, 1694509620=8.401434897869077E-4, 1694545620=8.438824499876583E-4, 1694581620=8.171293069653031E-4, 1694617620=8.596749524634415E-4, 1694653620=8.368097665295172E-4}}}
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  1.351 s
Finished at: 2023-09-28T14:13:13-05:00

相关问题