Home > front end >  Parsing string to JsonObject in Java
Parsing string to JsonObject in Java

Time:04-27

In my Java project I am constantly getting a string input such as "{type=01010201, capacity=700, auth_method=01, auth_no=090713}"

When I am trying to parse this string like below, it seems to fail

JsonObject tot_payload = null;
try {
    tot_payload = new JsonObject(obj.getString("data"));
} catch (Exception e) {
    log.error("record in json parsing error");
}

I understand that this is due to the fact that I am missing the spaces for the string. My application receives a variety of different strings like this and I was wondering if there would be any efficient way of turning such string into a json object.

CodePudding user response:

Assuming that it is org.json.JSONObject, preprocessing your input into actual JSON format should solve the problem:

import static org.assertj.core.api.Assertions.assertThat;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;

class JSONObjectLT {
    
    @Test
    void parseString() throws JSONException {
        
        final String input = "{type=01010201, capacity=700, auth_method=01, auth_no=090713}";
        
        // only works if keys/values do not contain equal signs
        final String preprocessed = input.replace('=', ':');
        final JSONObject json = new JSONObject(preprocessed);

        assertThat(json.getString("type")).isEqualTo("01010201");
        assertThat(json.getInt("capacity")).isEqualTo(700);
    }
}
  • Related