How to get Json Object without JsonArray name [duplicate] - java

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.

Related

Java parse all values from Array in JSON to ArrayList

I have a problem. I have the following JSON:
{
"Market":"USDT",
"Coin":"BTC",
"Period":"1h",
"EmergencyPerc":-25,
"TakeProfitPerc":1.2,
"ProtectiveOrdersEnabled":"no",
"EMACrossMarginPerc":0.5,
"EMABuySellPeriod":"15m",
"EMABuySellNameLow":"EMA10",
"EMABuySellNameHigh":"EMA50",
"EMAUnfreezePeriod":"1h",
"EMAUnfreezeNameLow":"EMA20",
"EMAUnfreezeNameHigh":"EMA200",
"SimTemplate":"t001",
"Patterns":{
"Buy":[
"buy_pattern_1",
"buy_pattern_2"
],
"Sell":[
"sell_pattern_1",
"sell_pattern_2"
]
}
}
I want to parse that JSON to the following class:
public class AgentStrategy {
private String Market;
private String Coin;
private double EmergencyPerc;
private double TakeProfitPerc;
private String ProtectiveOrdersEnabled;
public double EMACrossMarginPerc;
public String EMABuySellPeriod;
public String EMABuySellNameLow;
public String EMABuySellNameHigh;
public String EMAUnfreezePeriod;
public String EMAUnfreezeNameLow;
public String EMAUnfreezeNameHigh;
private String SimTemplate;
private ArrayList<PriceDropSell> PriceDropSells;
private ArrayList<String> buyPatternsUsed = new ArrayList<>();
private ArrayList<String> sellPatternsUsed = new ArrayList<>();
}
For that I have the following method inside that class:
public AgentStrategy parseJsonToObject(String jsonString) {
Gson gson = new Gson();
AgentStrategy agent = gson.fromJson(jsonString, AgentStrategy.class);
// PATTERNS
Map patternsMap = (Map) map.get("Patterns");
Map sellMap = (Map) patternsMap.get("Sell");
Map buyMap = (Map) patternsMap.get("Buy");
agent.buyPatternsUsed = new ArrayList<>(sellMap.values());
agent.buyPatternsUsed = new ArrayList<>(buyMap.values());
return agent;
}
But I get an error on this line at the pattern parse part:
agent.buyPatternsUsed = new ArrayList<>(sellMap.values());
With: Exception in thread "main" java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class java.util.Map (java.util.ArrayList and java.util.Map are in module java.base of loader 'bootstrap')
How can I parse all the patterns from buy and sell to a String Array (seperate)?
How can I parse all the patterns from buy and sell to a String Array (seperate)?
The JSON you posted has two arrays and you're trying to parse them as maps. Parse them as arrays (lists).
List sellList = (List) patternsMap.get("Sell");
List buyList = (List) patternsMap.get("Buy");
That said, the true power of GSON (and JSON parsers in general) is that do the heavy work for you if you model your classes correctly. You could have a "Patterns" class that has two lists of strings, then the strategy class would have a "Pattern". For example:
class Patterns {
List<String> Buy;
List<String> Sell;
}
class Agent Strategy {
Patterns Patterns;
}
Now, when you parse the object, because the class structure matches the json structure, the lists are parsed automatically for you:
AgentStrategy agent = gson.fromJson(jsonString, AgentStrategy.class);
// agent.Patterns.Buy and .Sell now have the lists
Then you could just define helpers to get the data you care about:
class Agent Strategy {
Patterns Patterns;
public getBuyPatternsUsed() { return Patterns.Buy; }
public getSellPatternsUsed() { return Patterns.Sell; }
}
P.S. - Tip: when you see "class cast exception" use your debugger to step through up to line where the crash happens and see what type you're actually getting compared to what you expect. That will help you debug your issue.
"Buy":[
"buy_pattern_1",
"buy_pattern_2"
],
"Sell":[
"sell_pattern_1",
"sell_pattern_2"
]
The Buy and Sell are arrays.
So the following cast will throw exception
Map sellMap = (Map) patternsMap.get("Sell");
Map buyMap = (Map) patternsMap.get("Buy");
Suggestion
Try to use annotations to map the java attribute name and json field name
i have only named few fields (using #SerializedName annotation)
static class PriceDropSell {
#SerializedName("Buy")
List<String> buy;
#SerializedName("Sell")
List<String> sell;
}
static class AgentStrategy {
private String Market;
private String Coin;
private double EmergencyPerc;
private double TakeProfitPerc;
private String ProtectiveOrdersEnabled;
public double EMACrossMarginPerc;
public String EMABuySellPeriod;
public String EMABuySellNameLow;
public String EMABuySellNameHigh;
public String EMAUnfreezePeriod;
public String EMAUnfreezeNameLow;
public String EMAUnfreezeNameHigh;
private String SimTemplate;
#SerializedName(("Patterns"))
private PriceDropSell Patterns;
}
public static void main(String[] args) {
Gson gson = new Gson();
AgentStrategy agentStrategy = gson.fromJson(str, AgentStrategy.class);
System.out.println(gson.toJson(agentStrategy));
}

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.

Java GSON deserializing array of objects

Im trying to deserialize a JSON string into an array of objects looking like this:
[{"ParentLocationName":null
,"Id":"String-Id"
,"Name":"String-Name"
,"ExternalId":null
,"LocationType":0
,"TimeZone":null
,"ParentLocationId":null}
,{"ParentLocationName":"String-Name"
,"Id":"String-Id2"
,"Name":"Child-Name"
,"ExternalId":null
,"LocationType":0
,"TimeZone":null
,"ParentLocationId":"String-Id"}
,{"ParentLocationName":null
,"Id":"String-Id3"
,"Name":"Some other name"
,"ExternalId":null
,"LocationType":0
,"TimeZone":null
,"ParentLocationId":null}]
so I have a class called Location with corresponding fields:
public class Location {
public String ParentLocationName;
public String Id;
public String Name;
public String ExternalId;
public int LocationType;
public String TimeZone;
public String ParentLocationId;
}
Where I am using Gson in the following way:
Gson gson = new Gson();
Location[] places = gson.fromJson(Json_As_String, Location[].class);
and I am receiving error:
Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]
Ive also tried using a collection like so:
Type collectionType = new TypeToken<>
Type colType = new TypeToken<Collection<Location>>(){}.getType();
Collection<Location> locs = gson.fromJson(Json_As_String,colType );
But receiving the same error.

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);

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

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;
}

Categories