How does Gson.fromJson(String, Class) work? - java

Consider following sample Json string :
{"Name":"val","FatherName":"val","MotherName":"val"}
I convert the above Json to the following pojo :
public class Info{
private String name;
private String father;
private String mother;
}
What I am wondering is, when I do the following :
Gson.fromJson(jsonLine, Info.class);
How are the keys in json object tracked to the variables in my pojo ? How is the value of the key FatherName stored in father in Info.class?

Gson is using the reflection(https://android.jlelse.eu/reflections-on-reflection-performance-impact-for-a-json-parser-on-android-d36318c0697c). So the example json will not work as expected in your example there are a couple of option to solve this
Change json string to {"name":"val","father":"val","mother":"val"}
Change the properties in the info class father-fatherName and the same for mother
3 Create a custom serializer GSON - Custom serializer in specific case
Thanks to #Aaron
you can also annotated the variables with #SerializedName
#SerializedName("father")
private string FatherName;

In Kotlin, having this class:
import com.google.gson.annotations.SerializedName
data class UsuariosDTO (
#SerializedName("data") var data: List<Usuarios>
)
data class Usuarios(
#SerializedName("uid") var uid: String,
#SerializedName("name") var name: String,
#SerializedName("email") var email: String,
#SerializedName("profile_pic") var profilePic: String,
#SerializedName("post") var post: Post
)
data class Post(
#SerializedName("id") var id: Int,
#SerializedName("date") var date: String,
#SerializedName("pics") var pics: List<String>
)
I'm able to use (where dataObteined is of UsuariosDTO type):
val json = gson.toJson(dataObtained)
And later deserialize the json like this:
val offUsuariosDTO = gson.fromJson(json, UsuariosDTO::class.java)
After looking everywhere I found out my error was UsuariosDTO.class. Since Gson is a java library you have to use UsuariosDTO::class.java

Related

Get Json Value from text

I have a REST response, which contains text and JSON value. I need to get uniqueId from JSON value, what will be the best way?
My JSON is very big, but looks like this:
paymentResponse = Published your custom Transaction json to topic env_txn_endtoend_01 Final json: {"txnId":null, "envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534" etc...}}
How can I get this uniqueId value = 234234_2344432_23442?
There are many libraries to help with Json Serialization and Deserialization. Jackson Object Mapper is one of the most popular ones.
The code would be something like this. To begin with you would need Java Pojo which represents your json Object e.g. let's consider this example from this tutorial, where you can create a Car Java Object from a Car json string.
ObjectMapper objectMapper = new ObjectMapper();
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class); // you should have a Car Class(Pojo) with color, and type attributes
Final json: {"txnId":null,
"envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534"
etc...}}
How can i get this uniqueId value = 234234_2344432_23442
You could do something like this:
import groovy.json.JsonSlurper
...
String jsonString = '{"txnId":null, "envelope":{"uniqueId":"234234_2344432_23442","rootID":"34534554534"}}'
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)
def envelope = json.envelope
String rootId = envelope.rootID
assert rootId == '34534554534'
String uniqueId = envelope.uniqueId
assert uniqueId == '234234_2344432_23442'

How to parse a application/x-www-form-urlencoded with an associative array?

I'm trying to parse the following body:
event=invoice.created&data%5Bid%5D=1757E1D7FD5E410A9C563024250015BF&
data%5Bstatus%5D=pending&data%5Baccount_id%5D=70CA234077134ED0BF2E0E46B0EDC36F&
data%5Bsubscription_id%5D=F4115E5E28AE4CCA941FCCCCCABE9A0A
Which translates to:
event = invoice.created
data[id] = 1757E1D7FD5E410A9C563024250015BF
data[status] = pending
data[account_id] = 70CA234077134ED0BF2E0E46B0EDC36F
data[subscription_id] = F4115E5E28AE4CCA941FCCCCCABE9A0A
Code:
#PostMapping(consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE])
fun cb(event: SubscriptionRenewed)
{
println(event)
}
data class SubscriptionRenewed(
val event: String,
val data: Data
)
data class Data(
val id: String,
val status: String,
val account_id: String,
val subscription_id: String
)
Normally you just create a POJO representation of the incoming body and spring a translates it to an object.
I learned that I could add all the parameters to the function declaration as #RequestParam("data[id]") id: String, but that would make things really verbose.
The issue is with parsing data[*], ideas of how to make it work?
Edit:
I discovered that if I change val data: Data to val data: Map<String, String> = HashMap(), the associative array will be correctly inserted into the map, ideas of how to map it to an object instead?
Note: IDs/Tokens are not real. They are from a documentation snippet.
Deserialize to Map and use json serialize/deserialize to object
Initially deserialize the input to Map<String, String>
Use Json processor(like ObjectMapper or Gson) to serialize the Map constructed in the previous step
Use the json processor to deserialize the json output of previous step to a custom object.
static class Data {
private String one;
private String a;
#Override
public String toString() {
return "Data{one=" + one + ", a=" + a + "}";
}
}
public static void main(String[] args) {
String input = "{\"one\":1, \"a\":\"B\"}";
Gson gson = new GsonBuilder().create();
Map<String, String> map = gson.fromJson(input, new TypeToken<Map<String, String>>(){}.getType());
Data data = gson.fromJson(gson.toJson(map), Data.class);
System.out.println(data);
}
This is surely a round about approach and i am not aware of any optimization

gson.toJson returns an empty object for a data class

I have a kotlin data class OfflineDataRequestInfo which I want to convert to Json using Gson, but it always returns an empty object
data class OfflineDataRequestInfo (
#SerializedName("status") val status: String,
#SerializedName("userId") val userId: String?,
#SerializedName("fulOrderId") val fulOrderId: String,
#SerializedName("timeStamp") val timeStamp: String,
#SerializedName("fulOrder") val fulOrder: String,
#SerializedName("checks") val checks: String?
)
some of the values could be null so I tried the bellow code too which returned {}
gson.toJson(OfflineDataRequestInfo("a","b","c","d", "e", "f"))
Here is a bit more info just in case that is an issue
#Entity
data class OfflineData (
#PrimaryKey(autoGenerate = true) val id: Int = 0,
#ColumnInfo(name="request_code") val requestCode: String?,
#Embedded
val requestInfoJson: OfflineDataRequestInfo
)
this is my actual function
fun postFulOurderData(offlineData: OfflineData) {
if (offlineData != null) {
val mainRepository = MainRepository(ApiHelper(RetrofitBuilder.apiService))
val builder = GsonBuilder()
builder.serializeNulls()
val gson = builder.create()
launch {
val postFulOrder = mainRepository.postFulOrderOfflineData(gson.toJson(offlineData.requestInfoJson), tokenResult.access_token)
}
}
}
I also tried using GsonBuilder as shown above and also the default Gson, but no luck
also tried gson.toJson(offlineData.requestInfoJson, OfflineDataRequestInfo::class.java)
can any one suggest please where I am doing it wrong
your help will be very much appreciated
thanks
R
Probably you have new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() setting for gson. If so you just need to add #Expose annotation to each field you want serialize in json:
data class OfflineDataRequestInfo (
#Expose #SerializedName("status") val status: String,
#Expose #SerializedName("userId") val userId: String?,
#Expose #SerializedName("fulOrderId") val fulOrderId: String,
#Expose #SerializedName("timeStamp") val timeStamp: String,
#Expose #SerializedName("fulOrder") val fulOrder: String,
#Expose #SerializedName("checks") val checks: String?
)
I don't know that much about Kotlin, but I do know that you can mix Java and Kotlin pretty well, and since Gson was made with Java use in mind I think you should use Java. You can create a Java class, and then a method like this:
String toJson(OfflineDataRequestInfo o) {
return new Gson().toJson(o, OfflineDataRequestInfo.class);
}
and then call that method from Kotlin.
I'm not saying that you should do your entire project in Java, just use Java for this one method.
Hope this helps, and please tell me if this wasn't what you had in mind :)
I just tested the following code using gson:2.2.4 and it works:
data class OfflineDataRequestInfo (
#SerializedName("status") val status: String,
#SerializedName("userId") val userId: String?,
#SerializedName("fulOrderId") val fulOrderId: String,
#SerializedName("timeStamp") val timeStamp: String,
#SerializedName("fulOrder") val fulOrder: String,
#SerializedName("checks") val checks: String?
)
fun main() {
println(Gson().toJson(OfflineDataRequestInfo("a","b","c","d", "e", "f")))
}
Output:
{"status":"a","userId":"b","fulOrderId":"c","timeStamp":"d","fulOrder":"e","checks":"f"}
I didn't try it on android, but it should also work.
I suggest you try to update your gson version and also to write a unit test using it.

Java Parse String

I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.

Reading JSON String using JSON/Gson

I have the JSON String of the below format which I get as a http request in Java. I need to get the name and values of the below JSON string, but I am not able to get the correct solution.
Can any one tell me how to parse this? Also, let me know if we will be able to format this string because there is no property names from the 3 element.
The string format is
{
'appname':'application',
'Version':'0.1.0',
'UUID':'300V',
'WWXY':'310W',
'ABCD':'270B',
'YUDE':'280T'
}
edit#1 formatted the question.
In JavaScript, you can do something like
var v = eval("("+data_from_server+")");
var aName = v.appname;
For example this script will alert appname.
<script>
var serverdata = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
var v = eval("("+serverdata+")");
alert(v.appname);
</script>
Based on your comment on this answer, here is a way to parse in Java
In Java, you may want to leverage GSon. See here.
You need to define a Java class that maps the JSON object one-to-one. Then ask GSon to create a Java object using the JSON String. Here is the example.
Your Java class that maps JSON should look like this
public class MyData{
public String appname;
public String Version;
public String UUID;
public String WWXY;
public String ABCD;
public String YUDE;
public MyData(){}
}
And you parse in Java like this.
String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
Gson gson = new Gson();
MyData obj = gson.fromJson(jsons, MyData.class);
System.out.println("ada "+ obj.appname);
With which language do you want to do that ?
Here is the solution for PHP :
$data = json_decode('the json');

Categories

Resources