Decode JSON file with Kotlin vs Swift [duplicate] - android

This question already has answers here:
Kotlin Data Class from Json using GSON
(3 answers)
Closed 4 years ago.
JSON decoding was improved in Swift4
you simply just call JSONDecoder().decode
and give it the json object and it will be converted into object
here is an example of that way
https://roadfiresoftware.com/2018/02/how-to-parse-json-with-swift-4/
my question that is there a way in Kotlin similar to the new way in Swift4 ?

Yes, Android has had that for quite a few years now.
It's a library from Google themselves, called GSON:
https://github.com/google/gson
Example:
Gson gson = new GsonBuilder().create();
gson.fromJson("MY JSON STRING", MyClass.class);
There are many overloads for the 'fromJson' function. There is also a 'toJson' function, to turn an object into a JSON string.
This is not just for Kotlin, it also works in Java.

Related

How to post params using retrofit android studio? [duplicate]

This question already has answers here:
Send Post Request with params using Retrofit
(6 answers)
Closed 4 years ago.
I need to send an array with Post Request using Retrofit. In Postman worked correctly like this
But in Android, I can not send the correct request.Please, help me.
UPDATE
I try like this:
#POST("/api/friends")
fun getContactsList(#Header("Authorization") token String,#Query("phones[]") phones : Array<String>) : Single<List<Friends>>
I think you can try this:
#POST("http://server/service")
Call<YourModel> postSomething(#Query("phones") List<String> array);
Generated url should look like this:
http://server/service?phones=123&phones=345&phones=567&phones=789

Moshi vs Gson in android [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm deciding on whether to use Moshi by square or Gson to serialize and deserialize model data.
one thing i always did not like about Gson is i think it uses reflection which can be slow on android? Does Moshi use reflection also?
What are some of the pros and cons of moshi vs Gson?
I see them as similar. take for example this statement that creates a typeAdapter:
class CardAdapter {
#ToJson String toJson(Card card) {
return card.rank + card.suit.name().substring(0, 1);
}
#FromJson Card fromJson(String card) {
if (card.length() != 2) throw new JsonDataException("Unknown card: " + card);
char rank = card.charAt(0);
switch (card.charAt(1)) {
case 'C': return new Card(rank, Suit.CLUBS);
case 'D': return new Card(rank, Suit.DIAMONDS);
case 'H': return new Card(rank, Suit.HEARTS);
case 'S': return new Card(rank, Suit.SPADES);
default: throw new JsonDataException("unknown suit: " + card);
}
}
}
and to use it register it just like in gson:
Moshi moshi = new Moshi.Builder()
.add(new CardAdapter())
.build();
I guess the advantages would be the annotation being used in the typeAdapter. I'm looking to find out if there are any performance gains if I switch to Moshi.
Moshi uses Okio to optimize a few things that Gson doesn’t.
When reading field names, Moshi doesn’t have to allocate strings or do hash lookups.
Moshi scans the input as a sequence of UTF-8 bytes, converting to Java chars lazily. For example, it never needs to convert integer literals to chars.
The benefits of these optimizations are particularly pronounced if you’re already using Okio streams. Users of Retrofit and OkHttp in particular benefit from Moshi.
Further discussion on the origins of Moshi are in my post, Moshi, another JSON Processor.
According to swankjesse's comment on reddit:
I’m proud of my work on Gson, but also disappointed by some of its limitations. I wanted to address these, but not as “Gson 3.0”, in part because I no longer work at Google.
Jake, Scott, Eric, and I created Moshi to address the various limitations of Gson. Here’s ten small reasons to prefer Moshi over Gson:
Upcoming Kotlin support.
Qualifiers like #HexColor int permit multiple JSON representations for a single Java type.
The #ToJson and #FromJson make it easy to write and test custom JSON adapters.
JsonAdapter.failOnUnknown() lets you reject unexpected JSON data.
Predictable exceptions. Moshi throws IOException on IO problems and JsonDataException on type mismatches. Gson is all over the place.
JsonReader.selectName() avoids unnecessary UTF-8 decoding and string allocations in the common case.
You’ll ship a smaller APK. Gson is 227 KiB, Moshi+Okio together are 200 KiB.
Moshi won’t leak implementation details of platform types into your encoded JSON. This makes me afraid of Gson: gson.toJson(SimpleTimeZone.getTimeZone("GMT"))
Moshi doesn’t do weird HTML escaping by default. Look at Gson’s default encoding of "12 & 5 = 4" for an example.
No broken Date adapter installed by default.
If you’re writing new code, I highly recommend starting with Moshi. If you’ve got an existing project with Gson, you should upgrade if that’ll be simple and not risky. Otherwise stick with Gson! I’m doing my best to make sure it stays compatible and dependable.
From the previous link you can see that using moshi codegen will create compile time adapters to model classes, which will remove the usage of reflection in runtime
Model
#JsonClass(generateAdapter = true)
class MyModel(val blah: Blah, val blah2: Blah)
app/build.gradle
kapt "com.squareup.moshi:moshi-kotlin-codegen:$version_moshi"
Will generate a MyModelJsonAdapter class with validations to ensure the nullablility of the model properties.

How to serialize ArrayList<Object> to String in Java Android

This question was asked many times, but I haven't found a good solution yet.
I want to store my Arraylist in the sharedpreferences in Android as a String. So how can I serialize and deserialize it?
Any solutions?
Try using Gson Library this way:
String json = new Gson().toJson(<your list>);
To add Gson library add to dependencies
compile "com.google.code.gson:gson:2.6.2"
You can supply a toString() method for your custom objects then call toString() on the ArrayList. Parsing the string to deserialize it will be more difficult.

How to start an android project coders view

I've been searching for the past week on how to develop an android project, read some on android developers page and on other websites like here, but no text was complete.
i have this project - i'm a php developer not a java, but could understand a bit about java lately.
the thing is i want to develop an android app using my website, i did output a json type data from my website, and gonna use them on the android app, i did the async request on android and could read the data form the website but :
first question: how to parse the json data correctly and convert it to array on android, i did that through:
Iterator<String> itr = myObject.keys();
while (itr.hasNext()) {
...
i don't know if that's the correct way, when i try to convert my json object to array, it gives me type mismatch.
second and more importantly:
how can create a "Block" like facebook posts style, or twitter style blocks, you know - blocks of json data, is it a linearlayout ? what do i call it ? and how can i add it to the UI dynamically, cuz these blocks are pulled from the website json data. so they are arrays...of blocks..
i'm kinda confused still, i need a start point.
Thank you!
excellent tutorial for beginners for android development
http://thenewboston.org/list.php?cat=6
and for your first question - how to parse json data correctly,
you can try using gson to convert the json data into POJO
otherwise you'd have to do myObject.opt(key) to make sure it is there
First question: you should use a library to parse JSON, it's simpler that way. Try gson. You should create a class, which holds the parsed object, like:
public class Taxi implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("idTaxi")
private Integer idTaxi;
#SerializedName("name")
private String name;
//getter, setters, constructor, etc
}
Then when you get the JSON object, you can parse it:
Gson gson = new Gson();
Reader reader = new InputStreamReader(SOURCE_STREAM);
Taxi[] response = gson.fromJson(reader, Taxi[].class);
Second question: i think a ListView would be good for you. You can read a full tutorial about it here

Parsing an object with variable type in gson

I have something like the following json string:
{"values" : [
{ "group":"A"
"rating":2
},
{
"group":"B"
"language":"english"
}
]
}
As you can see, "values" is an array, with different type of objects. One type can contain a string and an integer, and the other type contains a string and another string.
How do I deal with this?
Sorry, I didn't notice originally you wrote "gson". I'm not sure you can do it, and here's not me saying it.
Do some thing like the following
List myStrings = new ArrayList();
myStrings = gson.fromJson(json,myStrings.getClass());
Iterator myIterator = myStrings.iterator();
boolean b;
while(myIterator.hasNext()){
Object o =myIterator.next();
b=o instanceof String;
System.out.println("...."+b);
}
My approach would probably be to implement a polymorphic deserialization solution.
Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.
Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic:
Deserialising a generic with unknown compile time type where a field indicates the type
Parse JSON with no specific structure for a field with GSON
json object serialization/deserialization using google gson
Polymorphism with gson
Specific to the original question, it looks like the "group" element would be used to distinguish between different types.
FWIW, Jackson released a built-in solution to this problem many moons ago.

Categories

Resources