내 REST 애플리케이션의 응답에서 잘못된 JSON 형식

피에르 롤

내 REST 응용 프로그램에 응답을 반환하는 메서드가 있습니다. 특정 클래스 RestResponse를 사용하여 내 응답을 개인화 한 다음 'throw200Ok'를 사용하여 응답을 반환합니다.

@GET
@Path("/resultat/{id}")
public Response getResultat(@PathParam("id") int id) {
    Response response = null;
    RestResponse<JsonObject> restResponse = new RestResponse<JsonObject>();
    JsonObject jsonObject = null;

    "Some code"

    jsonObject = SMConverter.getResultat(socialChoices, list);
    restResponse.setData(jsonObject);
    response = restResponse.throw200Ok();

    return response;
}

SMConverter 클래스 :

public class SMConverter {

private static String RESULTATS = "resultats";
private static String STATS = "stats";

/**
 * Transform a SocialChoices and a list of vote which belong to him to a JsonObject which contain
 * the result and statistics
 * @param socialChoices
 * @param list
 * @return JsonObject
 */
public static JsonObject getResultat(SocialChoices socialChoices, List<Votes> list) {

    // Recover the number of choice
    int nbChoice = socialChoices.getValue().size();
    // Recover the number of voter
    int nbVoter = list.size();

    try {
        Matrix matrix = new Matrix(nbVoter, nbChoice);
        matrix.init();

        // Maps used to treat the response to clear informations
        HashMap<String, Integer> map = new HashMap<>();
        HashMap<Integer, String> mapReverse = new HashMap<>();

        for(int i = 0; i < nbChoice; i++) {
            // Map the i index to the choice i and put it in a HashMap
            String valueChoice = socialChoices.getValue().get(i).getName();
            map.put(valueChoice,i);
            mapReverse.put(i,valueChoice);
        }

        System.out.println(map);
        System.out.println(mapReverse);

        int choiceNb = socialChoices.getData().getInt("choiceNb");
        boolean ordered = socialChoices.getData().getBoolean("ordered");
        System.out.println(choiceNb);
        System.out.println(ordered);

        if (choiceNb > 1 && ordered) {
            for (int x = 0; x < nbVoter; x ++) {
                for (int j = choiceNb; j > 0; j--) {
                    // Recover the choice of each voter
                    String choice = list.get(x).getData().getString(Integer.toString(choiceNb-j+1));
                    // Use the map to get the index of the voter choice and map it to a tab
                    // Tab could be seen as a Matrix representing the choice of each voter
                    matrix.getTab()[map.get(choice)][x] = (byte) j;
                }
            }
            System.out.println(matrix);
            JsonObject jsonObject = treatment(ScrutinMajoritaireParSomme.voteScrutinMajoritaireParSomme(matrix),  mapReverse);
            System.out.println(jsonObject);

            return jsonObject;
        } else if ( !ordered ) {
            System.out.println("ok ok");
            for (int x = 0; x < nbVoter; x ++) {
                for (int j = choiceNb; j > 0; j--) {
                    // Recover the choice of each voter
                    // choiceNb-j+1 : because j start at choiceNb and not 1
                    String choice = list.get(x).getData().getString(Integer.toString(choiceNb-j+1));
                    // Use the map to get the index of the voter choice and map it to a tab
                    // Tab could be seen as a Matrix representing the choice of each voter
                    matrix.getTab()[map.get(choice)][x] = 1;
                }
            }
            System.out.println(matrix);
            JsonObject jsonObject = treatment(ScrutinMajoritaireParSomme.voteScrutinMajoritaireParSomme(matrix),  mapReverse);
            System.out.println(jsonObject);

            return jsonObject;
        }

    } catch (MatrixFormatException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * Transform a result to a clear and readable JsonObject
 * @param resu
 * @param map
 * @return
 */
public static JsonObject treatment(Resultat resu, HashMap<Integer, String> map) {

    JsonObjectBuilder resultats = Json.createObjectBuilder();
    JsonObjectBuilder stats = Json.createObjectBuilder();

    // For each result set the ranking and the choice to a readable name
    for (int i = 0; i < resu.getResultats().size(); i++) {
        resultats.add(Integer.toString(i+1),map.get(resu.getResultats().get(i+1)));
    }

    // For each statistics transform the key index to a readable name
    for (int j = 0; j < resu.getStats().size(); j++) {
        stats.add(map.get(j),resu.getStats().get(j));
    }

    JsonObject value = Json.createObjectBuilder()
            .add(RESULTATS,resultats.build())
            .add(STATS,stats.build())
            .build();

    return value;
}
}

다음에 해당하는 내 'jsonObject'변수 :

{"resultats":{"1":"a"},"stats":{"a":3,"b":1,"c":0}}

내 응답을 개인화하기위한 내 RestResponse 클래스. 내가 사용하는 'throw200Ok ()'메소드는 응답을 반환합니다.

public class RestResponse<T> implements Serializable {
private int httpErrorCode;
private T data;
private String errorMessage;
public static final String MEDIA_TYPE = MediaType.APPLICATION_JSON + ";charset=utf-8";


public RestResponse(){
    httpErrorCode = 200;
}

/**
 * Constructor by parameter
 * @param httpErrorCode
 * @param data
 * @param errorMessage
 */
public RestResponse(int httpErrorCode, T data, String errorMessage) {
    this.httpErrorCode = httpErrorCode;
    this.data = data;
    this.errorMessage = errorMessage;
}

public Response throw200Ok() {
    setHttpErrorCode(200);
    return Response.ok(this).type(MEDIA_TYPE).build();
}

public Response throw204NoContent(){
    setHttpErrorCode(204);
    return Response.status(Response.Status.NO_CONTENT).entity(this).type(MEDIA_TYPE).build();
}

public Response throw403Forbidden() {
    setHttpErrorCode(403);
    return Response.status(Response.Status.FORBIDDEN).entity(this).type(MEDIA_TYPE).build();
}

public Response throw404NotFound(){
    setHttpErrorCode(404);
    return Response.status(Response.Status.NOT_FOUND).entity(this).type(MEDIA_TYPE).build();
}

public Response throw405MethodNotAllowed() {
    setHttpErrorCode(405);
    return Response.status(405).entity(this).type(MEDIA_TYPE).build();
}

public Response throw409Conflict() {
    setHttpErrorCode(409);
    return Response.status(Response.Status.CONFLICT).entity(this).type(MEDIA_TYPE).build();
}

public Response throw412PreconditionFailed() {
    setHttpErrorCode(412);
    return Response.status(Response.Status.PRECONDITION_FAILED).entity(this).type(MEDIA_TYPE).build();
}

public Response throw500InternalServerError() {
    setHttpErrorCode(500);
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(this).type(MEDIA_TYPE).build();
}

public int getHttpErrorCode() {
    return httpErrorCode;
}

/**
 *
 * @param httpErrorCode
 */
private void setHttpErrorCode(int httpErrorCode) {
    this.httpErrorCode = httpErrorCode;
}

public boolean isSuccess() {
    return httpErrorCode == 200;
}

public T getData() {
    return data;
}

/**
 *
 * @param data
 */
public void setData(T data) {
    this.data = data;
}

public String getErrorMessage() {
    return errorMessage;
}

/**
 *
 * @param errorMessage
 */
public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
}
}

다음으로 REST 애플리케이션에서 'Response'를 반환합니다. 그리고 올바른 URL로 요청하고 있으며 내 응답은 다음과 같습니다.

{
"httpErrorCode": 200,
"data": {
  "resultats": {
    "1": {
      "chars": "a",
      "valueType": "STRING",
      "string": "a"
    }
  },
  "stats": {
    "a": {
      "integral": true,
      "valueType": "NUMBER"
    },
    "b": {
      "integral": true,
      "valueType": "NUMBER"
    },
    "c": {
      "integral": true,
      "valueType": "NUMBER"
    }
  }
},
"errorMessage": null,
"success": true
}

대신에 :

{
"httpErrorCode": 200,
"data": {
  "resultats":{"1":"a"},
  "stats":{"a":3,"b":1,"c":0}
},
"errorMessage": null,
"success": true
}
피에르 롤

해결책을 찾았습니다.

모든 RestResponse 메서드에서 "this"를 전달하는 대신 "this.toString"을 전달합니다. 또한 응답 표시를 제어하기 위해 'toString'메소드를 "@Override"로 설정했습니다.

return Response.status(Response.Status.ACCEPTED).entity(this.toString()).type(MEDIA_TYPE).build();

내 재정의 :

@Override
public String toString() {
    final StringBuilder sb = new StringBuilder("{");
    sb.append("\"httpErrorCode\":").append(httpErrorCode);
    sb.append(", \"data\":").append(data.toString());
    sb.append(", \"errorMessage\":").append(errorMessage);
    sb.append('}');
    return sb.toString();
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

애플리케이션 / json 유형 응답으로 잘못된 JSON 요청에 응답

분류에서Dev

JSON 응답 AJAX의 잘못된 형식

분류에서Dev

SOCKS 서버에서 Android Orbot 형식이 잘못된 응답

분류에서Dev

REST API의 응답이 내 코드에서 JSON 형식이 아닌데 Google 확장 "restman"이있는 올바른 형식 인 이유는 무엇입니까?

분류에서Dev

JSON 형식의 REST API 응답

분류에서Dev

JavaScript에서 잘못된 형식의 JSON 구문 분석

분류에서Dev

형식이 잘못된 JSON에서 백 슬래시 제거

분류에서Dev

Java에서 형식이 잘못된 JSON 구문 분석

분류에서Dev

REST 서비스 | JSON 응답 형식

분류에서Dev

Spring MVC Restful-잘못된 JSON 응답 형식

분류에서Dev

expressjs 애플리케이션 내부의 REST 요청에 https 사용

분류에서Dev

Angular 애플리케이션에서 typescript로 내부 JSON 읽기

분류에서Dev

왜 GRADLE이 내 Grails 애플리케이션의 잘못된 JAR 파일을 MAVEN 저장소에 업로드합니까?

분류에서Dev

내 정규식에 잘못된 이스케이프 시퀀스

분류에서Dev

Shopify 내에서 잘못된 JSON 데이터가 반환 됨

분류에서Dev

Swift에서 JSON 사용을 위해 형식이 잘못된 데이터 형식화

분류에서Dev

빌드 된 labview 애플리케이션 .exe 내의 대기열에 액세스

분류에서Dev

Android JSON 서버 응답이 잘못된 오류 일 수 있음

분류에서Dev

내 SQL 쿼리가 ExecuteNonQuery 메서드에서 형식이 잘못된 이유는 무엇입니까?

분류에서Dev

android-apollo의 응답에 잘못된 JSON 문자열

분류에서Dev

Android 애플리케이션 : 서버 콘텐츠의 잘못된 문자 집합

분류에서Dev

Android 애플리케이션 : 서버 콘텐츠의 잘못된 문자 집합

분류에서Dev

잘못된 정규 표현식, 이유 '{}의 잘못된 내용'이 R이있는 함수에서

분류에서Dev

잘못된 형식 일 때 Rails Controller에서 JSON 허용

분류에서Dev

400 (잘못된 요청) 오류가 발생하는 Java 애플리케이션에서 TFS REST API에 대한 HTTP PATCH 요청

분류에서Dev

내 Android 장바구니 애플리케이션의 서버로 JSON 배열 보내기

분류에서Dev

scapy로 UDP를 보내면 wireshark에서 잘못된 형식이 표시됩니다.

분류에서Dev

잘못된 JSON 응답

분류에서Dev

AJAX : 잘못된 JSON 응답

Related 관련 기사

  1. 1

    애플리케이션 / json 유형 응답으로 잘못된 JSON 요청에 응답

  2. 2

    JSON 응답 AJAX의 잘못된 형식

  3. 3

    SOCKS 서버에서 Android Orbot 형식이 잘못된 응답

  4. 4

    REST API의 응답이 내 코드에서 JSON 형식이 아닌데 Google 확장 "restman"이있는 올바른 형식 인 이유는 무엇입니까?

  5. 5

    JSON 형식의 REST API 응답

  6. 6

    JavaScript에서 잘못된 형식의 JSON 구문 분석

  7. 7

    형식이 잘못된 JSON에서 백 슬래시 제거

  8. 8

    Java에서 형식이 잘못된 JSON 구문 분석

  9. 9

    REST 서비스 | JSON 응답 형식

  10. 10

    Spring MVC Restful-잘못된 JSON 응답 형식

  11. 11

    expressjs 애플리케이션 내부의 REST 요청에 https 사용

  12. 12

    Angular 애플리케이션에서 typescript로 내부 JSON 읽기

  13. 13

    왜 GRADLE이 내 Grails 애플리케이션의 잘못된 JAR 파일을 MAVEN 저장소에 업로드합니까?

  14. 14

    내 정규식에 잘못된 이스케이프 시퀀스

  15. 15

    Shopify 내에서 잘못된 JSON 데이터가 반환 됨

  16. 16

    Swift에서 JSON 사용을 위해 형식이 잘못된 데이터 형식화

  17. 17

    빌드 된 labview 애플리케이션 .exe 내의 대기열에 액세스

  18. 18

    Android JSON 서버 응답이 잘못된 오류 일 수 있음

  19. 19

    내 SQL 쿼리가 ExecuteNonQuery 메서드에서 형식이 잘못된 이유는 무엇입니까?

  20. 20

    android-apollo의 응답에 잘못된 JSON 문자열

  21. 21

    Android 애플리케이션 : 서버 콘텐츠의 잘못된 문자 집합

  22. 22

    Android 애플리케이션 : 서버 콘텐츠의 잘못된 문자 집합

  23. 23

    잘못된 정규 표현식, 이유 '{}의 잘못된 내용'이 R이있는 함수에서

  24. 24

    잘못된 형식 일 때 Rails Controller에서 JSON 허용

  25. 25

    400 (잘못된 요청) 오류가 발생하는 Java 애플리케이션에서 TFS REST API에 대한 HTTP PATCH 요청

  26. 26

    내 Android 장바구니 애플리케이션의 서버로 JSON 배열 보내기

  27. 27

    scapy로 UDP를 보내면 wireshark에서 잘못된 형식이 표시됩니다.

  28. 28

    잘못된 JSON 응답

  29. 29

    AJAX : 잘못된 JSON 응답

뜨겁다태그

보관