简体   繁体   中英

How to convert a Json String/Data to a Java Class?

I'm new in Android and programming as well. I would like to build an Android app with user login and User Location tracer. What's the easiest way to convert a Json String to Java Class?

My Json String:

json字符串

You can use ObjectMapper

import com.fasterxml.jackson.databind.ObjectMapper;

public class YourClassDao {

private ObjectMapper objectMapper = new ObjectMapper();

  public YourClass load(String json) throws IOException {
    return objectMapper.readValue(
        json, YourClass.class);
  }

}

Couple of approaches I have used are:

  1. Using Jackson:

ObjectMapper objectMapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, UserDefinedClass.class);

  1. Using gson: gson is an open sourced java library used to serialize and deserialize Java objects to JSON. Import the library in maven
 <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency>
 private static Organisation getOrganisationObject() { String organisation = "{\"organisation_name\": \"TataMotors\", \"Employee\": \"2000\"}"; Gson gson = new Gson(); Organisation orgObject = gson.fromJson(OrganisationJson, Organisation.class); return orgObject; }

Three ways you can achieve this:

  1. String to JSON Object using Gson

The Gson is an open-source library to deal with JSON in Java programs. You can convert JSON String to Java object in just 2 lines by using Gson as shown below:

Gson g = new Gson();
YourClass c = g.fromJson(jsonString, YourClass.class)

You can also convert a Java object to JSON by using toJson() method as shown below

String str = g.toJson(c);


  1. JSON String to Java object using JSON-Simple The JSON-Simple is another open-source library which supports JSON parsing and formatting. The good thing about this library is its small size, which is perfect for memory constraint environments like J2ME and Android .

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);


  1. String to JSON - Jackson Example Jackson is I guess the most popular JSON parsing library in Java world. Following one-liner convert JSON string representing a soccer player into a Java class representing player:

YourClass obj = new ObjectMapper().readValue(jsonString, YourClass.class);

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