简体   繁体   中英

Parsing string to JsonObject in Java

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.

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);
    }
}

Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-json-org</artifactId>
    <version>2.13.2</version>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM