Java String to JSON conversion

后端 未结 4 917
遇见更好的自我
遇见更好的自我 2021-01-01 16:23

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :

相关标签:
4条回答
  • 2021-01-01 17:11

    The name is present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.

    JSONObject jObject  = new JSONObject(output); // json
    JSONObject data = jObject.getJSONObject("data"); // get data object
    String projectname = data.getString("name"); // get the name from data.
    

    Note: This example uses the org.json.JSONObject class and not org.json.simple.JSONObject.


    As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.

    Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.

    Sample from the link provided:

    JSONObject jsonObject = (JSONObject) obj;
    String name = (String) jsonObject.get("name");
    
    0 讨论(0)
  • 2021-01-01 17:19

    You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-

        StringBuilder buffer = new StringBuilder();
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            buffer.append(output);
        }
        output = buffer.toString(); // now you have the output
        conn.disconnect();
    
    0 讨论(0)
  • 2021-01-01 17:19

    Converting the String to JsonNode using ObjectMapper object :

    ObjectMapper mapper = new ObjectMapper();
    
    // For text string
    JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)
    
    // For Array String
    JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)
    
    // For Json String 
    String json = "{\"id\" : \"1\"}";
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser jsonParser = factory.createParser(json);
    JsonNode node = mapper.readTree(jsonParser);
    
    0 讨论(0)
  • 2021-01-01 17:23

    Instead of JSONObject , you can use ObjectMapper to convert java object to json string

    ObjectMapper mapper = new ObjectMapper();
    String requestBean = mapper.writeValueAsString(yourObject);
    
    0 讨论(0)
提交回复
热议问题