1

I am having a map

Map<String, Application.RiskFactor> appRiskFactorsMap = app.getRiskFactors();
    

It has this data kind of in it

{risk1=Application.RiskFactor(risk=risk1, question=question1,     
factor=true), risk2=Application.RiskFactor(risk=risk2,     
question=question2?, factor=true), 
risk3=Application.RiskFactor(risk=risk3, question=question3?, 
factor=true)}

I am converting it into JSON and having this output.

{"risk1":{"risk":"risk1","question":"question1?","factor":"true"},"":
{"risk":"risk2","question":"question2?","factor":"true"},"risk3":
{"risk":"risk3","question":"question3?","factor":"true"}}

I have this JSON converter class package system.referee.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class JsonUtils {

private static final ObjectMapper MAPPER = new ObjectMapper();

static {
    // Ignore unknown fields while deserialization
    MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    // Ignore null & Optional.EMPTY fields while serialization
    MAPPER.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
}

public static <T> String toJson(T obj) {
    try {
        return MAPPER.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        return "";
    }
}

public static <T> T fromJson(String json, Class<T> type) {
    try {
        return MAPPER.readValue(json, type);
    } catch (JsonProcessingException e) {
        return null;
    }
}
}

I want to print the JSON in this format

    {"risk":"risk1","question":"question1?","factor":"true"},
    {"risk":"risk2","question":"question2?","factor":"true"},
    {"risk":"risk3","question":"question3?","factor":"true"}

is there any way to achieve that? I am unable to find any help with this. thanks a lot

3
  • 1
    A JSON you want it is not valid. It should be an array I guess: [{"risk":"risk1",....]. Commented Oct 1, 2020 at 7:16
  • 1
    @MichałZiober if that could be produced, That's right. I might have mistyped it. Commented Oct 1, 2020 at 7:20
  • In that case it should be enough to serialise Map's values and ignore keys: JsonUtils.toJson (appRiskFactorsMap.values()). Commented Oct 1, 2020 at 7:22

1 Answer 1

1

You should ignore keys and serialise only values:

JsonUtils.toJson(appRiskFactorsMap.values())

Result will be a JSON Array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.