0

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 String

David0899
  • 37
  • 1
  • 7
  • do you want to parse your json file , you want to show these data from json to your app ! – Taki Jan 25 '21 at 18:01
  • check this https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – wolf Jan 25 '21 at 18:02

3 Answers3

2

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

}
volkangurbuz
  • 259
  • 1
  • 4
  • 14
0

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

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