How to use json parese this content - json

I got the json string like this,
{
"resultCode": 200,
"operation": 0,
"resultMsg": "正常初始化",
"debugMsg": "",
"resultCount": 3,
"result": {
"operation": 0,
"verify_key": "6f3e9169e4fcfbe4a52606c013348650",
"user_id": 41201
}
}
But I want to convert it to,
public class ClientResult {
String result;
String resultMsg;
String debugMsg;
int resultCode;
int operation;
}
.If i use gson.fromJson(result, ClientResult.class),get a exception
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 118
I just want to parse it to String, not Object, because the result field of ClientResut is not same,it maybe a array sometimes.
the result sometimes like
{
"resultCode": 200,
"operation": 0,
"resultMsg": "",
"debugMsg": "",
"resultCount": 12,
"result": {
"id": "4392",
"pm25": "44",
"time": "1433403001",
"l_temperature": "9",
"h_temperature": "20",
"c_temperature": "14",
"weather_icon": "http://60.31.215.212/zsgj/Public/weather/zhenyu.png",
"tm_l_temperature": "8",
"tm_h_temperature": "25",
}
}
So i just want to parse it to a String..

Its because you are doing it wrong, "result" is another json object in your json, You can go with an approach of creating 2 POJOs for your Json which you can use in your GSON.
public class Result
{
private String operation;
private String verify_key;
private String user_id;
}
and your original class
public class ClientResult
{
private String resultMsg;
private Result result;
private String debugMsg;
private String operation;
private String resultCount;
private String resultCode;
}

Related

deserialization of a JSON API response with moshi

I got a null object attributes after deserialization of a json response.
Developing under android, I'm using retrofit2 , moshi as converter (https://github.com/kamikat/moshi-jsonapi ) .
When debugging ,I saw a json response fully retrieved (not null attributes),but deserialization fails. Should I use GSON instead?
Here's my retrofit builder I use to make my json call: (no issue)
public static JsonServerInterface getSimpleClient(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_AUTH_URL)a
.addConverterFactory(MoshiConverterFactory.create())
.build();
JsonServerInterface webServer=retrofit.create(JsonServerInterface.class);
return webServer;
}
My api json call,response contain UserModel with null attributes(deserialization fails without any error)
signInCall.enqueue(new Callback<UserModel>(){
#Override
public void onResponse
(Call<UserModel> call, Response<UserModel> response)
{
response.message();
}
}
My UserModel (as required by moshi ,but I think it lacks something):
#JsonApi(type = "users")
public class UserModel extends Resource {
#Json(name = "auth-token")
private String authToken;
#Json(name = "firstname")
private String firstname;
#Json(name = "lastname")
private String lastname;
#Json(name = "email")
private String email;
#Json(name = "created-at")
private String createdAt;
#Json(name = "updated-at")
private String updatedAt;
private HasMany<ActivityModel> activities;
My json response I saw when debugging http response, I retrieve without any trouve,but moshi sucks to deserialize it,and no errors are raised:
{
"data": {
"id": "21",
"type": "users",
"attributes": {
"auth-token": "t8S3BTqyPwN3T4QDMY1FwEMF",
"firstname": "aymen",
"lastname": "myself",
"email": "aymen.myself#gmail.com",
"created-at": "2017-11-13T22:52:39.477Z",
"updated-at": "2017-11-13T23:21:09.706Z"
},
"relationships": {
"activities": {
"data": [
{
"id": "81",
"type": "activities"
}
]
}
}
},
"included": [
{
"id": "81",
"type": "activities",
"attributes": {
"title": "activity 10",
"description": "how to draw a circle",
"start-at": "2017-11-13T23:06:13.474Z",
"duration": 10,
"created-at": "2017-11-13T23:06:32.630Z",
"updated-at": "2017-11-13T23:06:32.630Z"
},
"relationships": {
"user": {
"data": {
"id": "21",
"type": "users"
}
}
}
}
]
}
I find the solution after lot of hours:
I should use "Document" instead of UserModel
interface:
#POST("sign-in.json")
Call<Document> signIn(#Body Credentials credentials);
when calling:
signInCall.enqueue(new Callback<Document>(){
#Override
public void onResponse(Call<Document> call, Response<Document> response) {
hope it helps

How automatically parse response String into Map using RestTemplate

I'm using RestTemplate to retrieve list of issues from Jira. As response I get String with lots of fields, some of them are arrays. Request looks like:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
Response string looks like:
{
"expand": "schema,names",
"total": 12,
"issues": [
{
"id": "32",
"key": "TEST-1",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-02"
}
]
},
{
"id": "32",
"key": "TEST-2",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-01"
}
]
}
]
}
Is it possible to convert this String into Map, where Object could be String or List of Map or something like this, without defining appropriate objects. As result, I'd like to have possibility to access description by: response.getIssues().get(0).getFields().getFixVersion().get(0).getDescription()
In such occasion, defining chain of specific objects looks too cumbersome.
You can create your own POJO classes which corresponds to the structure of the response JSON.
Based on the json that you have shared, you can have a class structure like this :
public class Response {
private String expand;
private String total;
private List<Issues> issues;
}
public class Issues {
private String id;
private String key;
private Map<String, List<FixVersions> fields;
}
public class FixVersions {
private String description;
private String releaseData;
}
Your GET call will change to the following :
ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET, entity, Response.class);
P.S. - All the fields in the POJO class must have their getters and
setters as well.

Spring boot JSON response

Here's my code
#RequestMapping("/bookList")
public List<Books> list() {
return bookService.booksList();
}
public class Books {
private String author;
private String isbn;
private String title;
}
Current response
[["TOM",123456,"ABC"],["JANE",789000,"CDE"]]
Expected response
"Books": [
{"author": "TOM", "isbn": "123456", "title": "ABC"},
{"author": "JANE", "isbn": "789000", "title": "CDE"}
]
What is the code change I need to make?
Your List<Books> is correctly returned as JSON. Your option would be to wrap it into another object:
public class BookList {
public List<Books> books;
}
and return a BookListinstead of List<Books>.
But to be honest, I would not recommend you do do that. It's not very restful.
session.createQuery returns Object[]. I used Criteria query with projections inside my DAOIMPL class and I got the expected output.

Json Parsing with Lib Gson in Java

I'm trying to parse this json captured through an API of my client:
[
{
"pagination": {
"page": 7,
"total_pages": 11,
"entries": 100,
"total_entries": 1007
},
"logical_numbers": [
{
"logical_number": {
"id": 50095,
"number": "524103650",
"app_version_ids": [
1427,
1230,
847
],
"created_by": 1510,
"created_via": "interface",
"group_id": 526,
"created_at": "2016-03-21T15:54:30.670-03:00",
"updated_at": "2016-03-21T15:54:30.682-03:00"
}
},
{
"logical_number": {
"id": 44593,
"number": "524103627",
"app_version_ids": [
1427,
1230,
847
],
"created_by": 1510,
"created_via": "interface",
"group_id": 526,
"created_at": "2016-02-26T10:02:20.561-03:00",
"updated_at": "2016-02-26T10:02:20.608-03:00"
}
}
]
}
]
Here are the classes I created for this work:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
Gson gson = new Gson();
Pagination[] pagination = gson.fromJson(new FileReader("input1.json"), Pagination[].class);
System.out.println(gson.toJson(pagination));
}
}
class Pagination {
Long page;
Long total_pages;
Long entries;
Long total_entries;
ArrayList<LogicalNumbers> logicals;
}
class LogicalNumbers {
int id;
String number;
ArrayList<String> app_version_ids = new ArrayList<>();
String created_by;
String created_via;
String group_id;
String created_at;
String updated_at;
}
When I run this code, I get the following result:
[{}]
I'm not succeeding in the parsings. Can anybody help me?
Thanks.
After exploring the json I found the reason of the empty deseralization...
you have two small problems...
1st one:
your json is actually an array with one object that contains a Pagination
object and a logical numbers array
2nd: the POJO description of the json schema is not correct..
after a while I found a solution:
Try:
class Foo {
private Pagination pagination;
private List<LogicalNumbers> logical_numbers;
}
class Pagination {
Long page;
Long total_pages;
Long entries;
Long total_entries;
}
class LogicalNumbers {
Ln logical_number;
}
class Ln {
int id;
String number;
List<String> app_version_ids = new ArrayList<>();
String created_by;
String created_via;
String group_id;
String created_at;
String updated_at;
}
and then
public static void main(String[] args) {
Gson gson = new Gson();
Foo[] pagination = gson.fromJson(new FileReader("input1.json"), Foo[].class);
// Pagination[] pagination = gson.fromJson(new FileReader("input1.json"), Pagination[].class);
System.out.println(gson.toJson(pagination));
}

Json/Apex: Assigning values to nodes on the Json Array

I have an apex code that defines the JSON structure. I would like to seek for advice on how I will be able to assign values to the string fields on the JSON using Apex. The JSON will have an array (PackageData) which contains the fields that should contain the values
Apex code:
public class Shipment{
public PackageData[] PackageData;
}
public class PackageData{
public Packaging Packaging;
public Dimensions Dimensions;
public PackageWeight PackageWeight;
}
public class Packaging{
public string Code;
}
public class Dimensions{
public UnitOfMeasurement UnitOfMeasurement;
public string Length;
public string Width;
public string Height;
}
public class UnitOfMeasurement{
public string Code;
}
public class PackageWeight{
public UOM UOM;
public string Weight;
}
public class UOM{
public string Code;
}
JSON:
{
"PackageData": [
{
"Packaging": {
"Code": ""
},
"Dimensions": {
"UnitOfMeasurement": {
"Code": ""
},
"Length": "",
"Width": "",
"Height": ""
},
"PackageWeight": {
"UOM": {
"Code": ""
},
"Weight": ""
}
}
]
}
JSON are always string, so there are a parser which parse object to JSON String and vice versa
Parser does it's job and automatically parse to String, You need not worry for that
Json to Object:
ClassName objName = (ClassName) System.JSON.deserialize(jsonString, ClassName.class);
Object to Json:
String jsonString = System.JSON.serialize(objName);