I already have PHP to pull the info from MySQL and encode to json, example output below:
[{"name":"Player A","score":1459},{"name":"Player B","score":1434}]
I'm struggling to follow guides where I can parse this into a listview. For a start, it seems massively overcomplicated, needing custom adapters, large custom classes defining everything etc
Am I being naive thinking there should be an easy way to read this data from a URL and assign to a listview? I only need name and score fields for a basic scoreboard.
Even if I could just split the entire output up into strings, this would be more than enough as I could then do textview.setText(string1) and so on ...
If anyone has a working example of pulling json from a URL and being able to either pass this to a listview, or if its simpler, to be able to pass the output to strings?
Better use RecyclerView for parsing the json data.This link is the most simplest way to parse the json data.
http://androidcss.com/android/fetch-json-data-android/
Try it :)
Create a class SimpleModel.java
public class SimpleModel {
private int score;
private String name;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and parse it using Gson like this
String YOUR_RESPOSE_STRING = "";
Gson gson = new Gson();
Type lisType = new TypeToken<ArrayList<SimpleModel>>() {
}.getType();
ArrayList<SimpleModel> list = gson.fromJson(YOUR_RESPOSE_STRING, lisType);
Related
I need some Java help.
I have got a class like this
public class Thing {
private String name;
private int price;
public Thing(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And my main looks like this
public class Main {
public static void main(String[] args) {
Thing Bowl = new Thing("Bowl", 20);
} }
What I would like to do is make a simple XML-document database. So I can add different kind of things in my database. How can I implement this kind of database in my system?
It's not correct to call what you're talking about a database. You just want to save a Java class as an XML file. Jackson is a good library that allows for both JSON and XML encode/decode and using it, can be done as so given a POJO:
ObjectMapper xmlMapper = new XmlMapper();
List<Thing> things = new ArrayList<>();
things.add(bowl);
String xmlData = xmlMapper.writeValueAsString(things);
List<Thing> thingsFromXml = xmlMapper.readValue(xmlData, new TypeReference<List<Thing>>(){});
Although the question is very broad, I'll do my best to guide you along.
An overarching system for XML consists out of various subsystems. First of all, you're going to need a way to parse the XML documents. There are many open source libraries out there that you can use. Even if you insist on writing it from scratch, referencing work that others have made is always useful.
See this:
Which is the best library for XML parsing in java
Then once you have a system in place in which you can parse the documents, you'll need a way to organize the parsed data. The way to approach this is subject to the practical use of the system. For example, if you use XML as the standard format for loading data in a game and thus deal with many different types of data such as items, objects, locations and so forth. You'll want a dynamic way to reload the data, the factory design pattern would work well in this use-case.
See this: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
I'm calling an API of some service and they return a gigantic JSON with literally around a hundred of fields and a dozen of nested objects. However, I don't need all of them. In fact, when doing GET or POST I really need from 3 to 7 fields. I very much want to avoid having this complex model in my application just to serialize/deserialize a couple of fields.
Essentially, I wanted to achieve:
Deserialize their gigantic nested JSON string to my flat POJO.
Work in my code with my flat POJO projection.
Serialize my flat POJO to their complex nested schema.
My solution so far was to rely on JsonPath:
Create a custom annotation for fields in my flat POJO, like:
#JsonPathField("$.very.deeply.nested.field.value")
private String theOnlyFieldIneed;
Create a util method that uses reflection to produce a map of <fieldName, JsonPath.readValue()> which I give to Jackson objectMapper to produce my POJO. So deserialization to a flat POJO part works.
For serialization, however, things are worse, because JsonPath throws an exception if the path doesn't exist in the String. Like,
// This will throw an exception:
DocumentContext document = JsonPath.using(jsonPathConfig).parse("{}");
document.set("$.not.even.deepest", value);
To workaround that, I added kinda original schema as a string to feed to JsonParh.parse(Pojo.Prototype) but this is ugly, tedious and error-prone.
Basically, I'm looking for Immutable.JS kind of behaviour: Collection.SetIn
You could use Kson (https://github.com/kantega/kson) which has a pretty straighforward support for extracting values from nested structures.
public class DecodeExample {
public static class Address {
final String street;
final String zip;
public Address(String street, String zip) {
this.street = street;
this.zip = zip;
}
}
static class User {
final String name;
final Address address;
User(String name, Address address) {
this.name = name;
this.address = address;
}
}
public static void main(String[] args) {
final JsonDecoder<Address> adressDecoder =
obj(
field("street", stringDecoder),
field("zip", stringDecoder.ensure(z -> z.length() < 5)), //You can add constraints right here in the converter
Address::new
);
JsonResult<JsonValue> json =
JsonParser.parse(jsonString);
Address address =
json.field("model").field("leader").field("address").decode(adressDecoder).orThrow(RuntimeException::new);
System.out.println(address);
JsonResult<Address> userAddress =
json.field("model").field("users").index(0).field("address").decode(adressDecoder);
System.out.println(userAddress);
}
}
As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}
First, im a begiiner in GSON so please bear with me.
I have a set of classes with this structure :
class Response
Data data;
class Data
List<Item> items;
class Item
String id;
String title;
Private Player;
class Player
String mobile;
Im using those class to retrieve the JSON with GSON library.
I successfully retrieve the JSON data with this code :
Gson gson = new Gson();
Response myResponse = gson.fromJson(inputStreamReader, Response.class);
When i debug the code, i can see the Item class value is successfully retrieved inside the myResponse. However, i have a problem when i want to access the title variable in the Item Class because all i have is a Response Class.
How to get the title variable in the Item Class?
Any help is apprciated, Thanks for your help.
If you have public attributes (which is usually a bad practice!) you can just do:
//This will iterate over all items
for (Item item : myResponse.data.items) {
//for each item now you can get the title
String title = myItem.title;
}
Anyway, as I said, you should make your attributes private, and have getters and setters for those attributes. That's Java basics!
Namely, in your Response class, you should have something like:
private Data data;
public Data getData(){
return this.data;
}
public void setData(Data data){
this.data = data;
}
In the same way, you should have private attributes and getters and setters in all your classes.
So now you can access your items in the proper way with:
//Get the Data object with the getter method
Data data = myResponse.getData();
for (Item item : data.getItems()) {
String title = myItem.getTitle();
}
You can fetch the data like this:-
Data myData = myResponse.getData();
for(Item myItem : myData.getItems()){
// myItem.getTitle(); will give you the title from each Item
}
This is assuming that you've getters for all the fields in the classes.
can tell me if android have the same lib link
https://github.com/icanzilb/JSONModel
or
http://www.touch-code-magazine.com/JSONModel/
I parse JSON only need write set and get, and then make JSON to object mapping and serialization.
Check Gson and Jackson. Both are very easy to use, I prefer Gson because it works without annotations in the POJOs. There's lots of examples to be found on how to use them to serialize and deserialize JSON.
Gson does a great job for this;
You can read a little tutorial about it here which should get you started;
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
You also have Genson lib that has nice features, perfs, provides alternatives to annotations and is easy to use.
I would recommend the lib FastJson , it is fast than protocol buf and jackson , you can try this .
maybe FastPojo help you, a wilde card pojo class
https://github.com/BaselHorany/FastPojo
usually you make a modle class like this
public class Msg {
private int id;
private String name;
private Double doub;
private Boolean bool;
public Msg(String id,.....,.........) {
this.id = id;
........
}
public String getId() {
return id;
}
........
public void setId(String id) {
this.id = id;
}
........
}
for each variable you define its type and make setter and getter voids and pass it in a Routine process and then you use it like this usually
//set
Msg msg = new Msg();
msg.setId(id);
msg.setName(name);
........
//get
msg.getId();
.........
BUT with FastPojo you dont need custom modle because it is a "Wilde Card class" that can define objects type and then set and get them appropriately you just set and get directly> so:
Usage
just copy the class to your project
FastPojo msg = new FastPojo();
msg.set1(id);
msg.set2(name);
msg.set3(1.55);
msg.set4(true);
//get first variable where s is the type you should remember it s for string, i for int, d for double and b for boolean.
msg.get1i();//get id int
msg.get2s();//get string name
msg.get3d();//get double 1.55
msg.get4b();//get boolean true