简体   繁体   中英

How to convert Json String to Java Object?

I have following json in String format. How to convert it to a java object?

JSON Srting

String allCameraList =   [{
    "name": "Camera1",
    "displayURL": "Stream-1"
}, {
    "name": "Camera2",
    "displayURL": "Stream-3"
}, {
    "name": "Camera4",
    "displayURL": "Stream-7"
}, {
    "name": "Camera3",
    "displayURL": "Stream-5"
}, {
    "name": "Camera5",
    "displayURL": "Stream-10"
}, {
    "name": "Camera6",
    "displayURL": "Stream-12"
}]

Java Entity class

public class CameraDetails
{
    private String name;
    private String displayURL;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDisplayURL() {
        return displayURL;
    }

    public void setDisplayURL(String displayURL) {
        this.displayURL = displayURL;
    }}

When I tried to use Json parser like following:

 JsonParser parser = new JsonParser();
    String json = parser.parse(allCameraList)
            .getAsJsonObject()
            .getAsJsonObject("name")
            .toString();

it threw the following exception:

java.lang.IllegalStateException: Not a JSON Object

Please note that my json string is start with [ not with { .

You can convert a String to Json array.

ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(allCameraList);
JSONArray json = (JSONArray) parser.parse(jsonInString);

Take a look to this also.

import org.codehaus.jackson.map.ObjectMapper;

static ObjectMapper mapper=new ObjectMapper();
public ObjectMapper  getMapperObject(){
   return mapper;
}

mapper=TypeConvertion.getMapperObject();
String jsonString=mapper.writeValueAsString(allCameraList);
List<CameraDetails> newMSExp=mapper.readValue(jsonString, new TypeReference<List<CameraDetails>>() {});
return newMSExp;

You can't really define string without using escape character '/' and double quotes to begin with. You can read it from file, convert it to string as below :

private static String readFile(String path, Charset encoding)
        throws IOException
{
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

You can use StandardCharsets.UTF_8 as encoding method

Next, you can do a post-processing on the string obtained. For your use-case the code below should work.

private static String postProcess(String string) {
    String result;
    result = string.substring(1,string.length()-1);
    return  "{" + result + "}";
}

You can parse as a JSON after these steps.

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