JSON.stringify in java - android

后端 未结 3 1995
天命终不由人
天命终不由人 2021-01-03 22:43

Is there any way to perform a JSON.stringify in android?

I keep seeing JSON.stringify(JSONObject) all around the web, but I cant find the J

相关标签:
3条回答
  • 2021-01-03 23:19

    JSON.stringify(JSONObject) is a Javascript function and will not be available in Java. If you're using the org.json.* package built in the Android SDK, the equivalent would be to simply call toString() on your JSONObject instance, or the more human-friendly toString(int).

    http://developer.android.com/reference/org/json/JSONObject.html#toString() http://developer.android.com/reference/org/json/JSONObject.html#toString(int)

    JSONObject obj = ...
    String jsonString = obj.toString(4);
    
    0 讨论(0)
  • 2021-01-03 23:24

    I know this is old, but I ran into the same problem. And there doesn't seem to be much about it here... so I thought I would add what I learned.

    I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here.

    For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl

    Choose the version your project needs. (Typically you can go with the latest stable build).

    Once they are imported in to your project's libraries, add the following import lines to your code:

     import org.codehaus.jackson.JsonGenerationException;
     import org.codehaus.jackson.map.JsonMappingException;
     import org.codehaus.jackson.map.ObjectMapper;
    

    With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

    User u = new User();
     u.firstName = "Sample";
     u.lastName = "User";
     u.email = "sampleU@example.com";
    
    ObjectMapper mapper = new ObjectMapper();
        
    try {
        // convert user object to json string and return it 
        return mapper.writeValueAsString(u);
    }
    
      // catch various errors
      catch (JsonGenerationException e) {
        e.printStackTrace();
    } 
      catch (JsonMappingException e) {
        e.printStackTrace();
    }
    

    The result should looks like this: {"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}

    0 讨论(0)
  • 2021-01-03 23:24

    Basic actions with JSON objects in JAVA can be done either with a help of org.json package (included in Android SDK) or javax.json (part of JAVA EE). Both of them have toString() method for conversion of JSONObject to string:

    //assuming you have object `jsonobject` of class `JSONObject`
    String output = jsonobject.toString()
    
    0 讨论(0)
提交回复
热议问题