How to convert JSON string to custom object? [duplicate] - java

This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 9 years ago.
I've string like this (just )
"{\"username":\"stack\",\"over":\"flow\"}"
I'd successfully converted this string to JSON with
JSONObject object = new JSONObject("{\"username":\"stack\",\"over":\"flow\"}");
I've a class
public class MyClass
{
public String username;
public String over;
}
How can I convert JSONObject into my custom MyClass object?

you need Gson:
Gson gson = new Gson();
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);
also what might come handy in future projects for you:
Json2Pojo Class generator

You can implement a static method in MyClass that takes JSONObject as a parameter and returns a MyClass instance. For example:
public static MyClass convertFromJSONToMyClass(JSONObject json) {
if (json == null) {
return null;
}
MyClass result = new MyClass();
result.username = (String) json.get("username");
result.name = (String) json.get("name");
return result;
}

Related

How to get Json Object without JsonArray name [duplicate]

This question already has answers here:
Simple parse JSON from URL on Android and display in listview
(6 answers)
Get JSONArray without array name?
(4 answers)
Parsing json array with no name in android [closed]
(4 answers)
Closed 4 years ago.
I am trying to parse the JSON data retrieved from the following link
http://fipeapi.appspot.com/api/1/carros/marcas.json
It does not have a name of the JsonArray. Here is what I have tried so far.
private String getName(int position) {
String name = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
And here is the Config class
public class Config {
//JSON URL
public static final String DATA_URL = "http://fipeapi.appspot.com/api/1/carros/marcas.json";
//Tags used in the JSON String
public static final String TAG_USERNAME = "name";
public static final String TAG_NAME = "fipe_name";
public static final String TAG_COURSE = "key";
public static final String TAG_ID_MARCA_CARRO = "id";
//JSON array name
public static final String JSON_ARRAY = "marcas";
}
Please let me know if you need more information to help me in solving this problem. Thanks in advance!
The easier way to parse a JSON data in Android is using Gson. It is simple and easier to integrate with your code. You just need to add the following dependency in your build.gradle file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Now in your code, you need to create the following class.
public class Car {
public String name;
public String fipe_name;
public Integer order;
public String key;
public Long id;
}
Now simply parse the JSON string you have like the following.
Gson gson = new Gson();
Car[] carList = gson.fromJson(jsonResponse, Cars[].class);
You will find the JSON parsed as an array of objects. Hope that helps.

JSON to List<T> [duplicate]

This question already has answers here:
How to convert JSON string into List of Java object?
(10 answers)
Why can't I unwrap the root node and deserialize an array of objects?
(3 answers)
Closed 5 years ago.
im new here and have a problem, surprise surprise :D
I have a JSON String and i want to convert it into a List.
My JSON String:
{
"results": [
{
"uri": "http://xxxxxx",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.438+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},
{
"uri": "http://yyyyyyy",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.560+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},]}
How can i convert it in Java?
EDIT:
My Problem was the "results" Root-Element...
this
worked fine.
First you need to make a Java model object which matches the model in your JSON e.g.:
public class MyClass {
private String uri;
private int downloadCount;
private ZonedDateTime lastDownloaded;
private int remoteDownloadCount;
private ZonedDateTime remoteLastDownloaded;
(getters and setters)
}
Then you can use a JSON parser like Jackson (https://github.com/FasterXML/jackson) to parse your JSON as a list of instances of this object using the Jackson ObjectMapper class (https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html):
ObjectMapper objectMapper = new ObjectMapper();
MyClass[] myClasses = objectMapper.readValue(jsonString, MyClass[].class);
Create a class for accessing data.
class ListElement {
public String uri;
public int downloadCount;
public String lastDownloaded;
public int remoteDownloadCount;
public String remoteLastDownloaded;
}
Then, parse the json and get the list and convert it to list.
public static void main(String[] args) throws ParseException {
Gson gson = new Gson();
JsonElement list = new JsonParser().parse(json).getAsJsonObject().get("results");
List<ListElement> listObj = gson.fromJson(list, new TypeToken<List<ListElement>>() {}.getType());
System.out.println(listObj.size());
}
Note that I used String instead of ZonedDateTime. Since, its a String(enclosed between quotes) for JsonObject.

JSON to a Java collection [duplicate]

This question already has answers here:
How do I convert a JSON array into a Java List. I'm using svenson
(4 answers)
Closed 5 years ago.
I got JSON like
{
"items":[
{
"id":15
,"name":"abc"
}
,{
"id":16
,"name":"xyz%"
}
,{
"id":17
,"name":"qwerty"
}
,{
"id":18
,"name":"rudloph"
}
,{
"id":19
,"name":"jane"
}
,{
"id":20
,"name":"doe"
}
]
}
I have class which is like:
public class Foo {
public String id;
public String name;
}
And I want to convert this JSON into List<Foo>. How can i do this? Right now I am doing like:
List<Foo> fooList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONArray araray = jsonObject.getJSONArray("items");
for(int i =0 ; i < araray.length();i++){
Foo dto = new Foo();
dto.setId(Long.valueOf((String) araray.getJSONObject(i).get("id")));
dto.setName((String) araray.getJSONObject(i).get("name"));
fooList.add(dto);
}
PS: Cannot change JSON. Jackson or Gson. Please let me know with code example.
i think you need to use the java json api and you need bind it manually
If you use gson, you may use TypeToken to load the json string into a custom Foo object.
List<Foo> objects = gson.fromJson(source, new TypeToken<List<Foo>>(){}.getType());
source can be String or BufferedReader.
You are having the wrong model for the JSON String. actually the list of Foo is inside another Model. Simply write another class like
public class Item {
List<Foo> items;
public Item() {
}
// getter setter
}
Now you can use com.fasterxml.jackson.databind.ObjectMapper like this
ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(json, Item.class);
for(Foo foo : item.getItems()) {
...
}
Try this with GSON.
Gson gson = new Gson();
Map<String, List<Foo>> objects = gson.fromJson(source,
new TypeToken<Map<String, List<Foo>>>(){}.getType());
List<Foo> list = objects.get("items");

Java self unserialization

I am trying to write a class, that has exportToString and importFromString methods. ExportToString serializes this class to JSON string:
public String exportToString() {
Gson gson = new Gson();
String json = gson.toJson(this);
return json;
}
I need to write importFromString(String str). The problem is that "this" variable is final and I can't reassign this value completely. This is what I have:
public void importFromString(String str) {
Gson gson = new Gson();
Object obj = gson.fromJson(str, this.getClass());
this = (PlayerData) obj; // ERROR: cannot assign value to final variable this
}
P.S. Sorry for my english
I think the simplest way to do what you want is to make the second method static and return an instance of the object represented in the string:
public static PlayerData importFromString(String str) {
Gson gson = new Gson();
Object obj = gson.fromJson(str, PlayerData.class);
return (PlayerData) obj;
}
You then invoke it as follows:
PlayerData obj = PlayerData.importFromString(someString);
Something like this maybe?
public static PlayerData importFromString(String str) {
Gson gson = new Gson();
Object obj = gson.fromJson(str, PlayerData.class);
return (PlayerData) obj;
}

How to parse json data using in java

I am getting this data from server how to parse this data in java .
LabelField jsonResult = new LabelField(connectJson.response);
"[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]"
I am getting response in jsonResult variable
You can use libraries like Jackson to do the same. There is also Google's GSON which will help you do the same. See this example
Take a look at the JSONParser Object in this Tutorial
If you are using Eclipse plugin than may JSON library included in you SDK.
Use below code to parse your JSON string got from the server.
String test = "[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]";
JSONArray array = new JSONArray(test);
JSONObject obj = (JSONObject) array.get(0);
Your String look like you got JSON Array from the server.
First convert your Json string to JSON Array by
JSONArray array = new JSONArray(Your JSON String);
Each element in array represent JSON Object.You can read JSON Object by
JSONObject obj = (JSONObject) array.get(Index);
You can read parameter from Object to any String variable by :
String valueStr = obj.getString("screen_refresh_interval");
May this help you.
Design a class (viz CustomClass) first with screen_refresh_interval and station_list_last_update as properties. And Make a collection class for CustomClass
I'm using Gson as deserializer. Other libraries are also available.
public class Container {
private CustomClass[] classes;
public CustomClass[] getClasses() {
return classes;
}
public void setClasses(CustomClass[] classes) {
this.classes = classes;
}
}
public class CustomClass {
private String screen_refresh_interval;
private String station_list_last_update;
public String getScreen_refresh_interval() {
return screen_refresh_interval;
}
public void setScreen_refresh_interval(String screen_refresh_interval) {
this.screen_refresh_interval = screen_refresh_interval;
}
public String getStation_list_last_update() {
return station_list_last_update;
}
public void setStation_list_last_update(String station_list_last_update) {
this.station_list_last_update = station_list_last_update;
}
}
Gson gson = new Gson();
Container customClassCollection = gson.fromJson(jsonResult, Container.class);

Categories