Android: KeyValuePairs to json - java

Is there some easy way of transforming KeyValuePairs into json
For Example
{ "keyvaluepairs" :
{ "long": "6,5",
"heavy": "200",
}
}
long and heavy are inside the keyvaluepairs? some easyway of doing this?

I'm not sure exactly what data structure you mean by KeyValuePairs, but presumably you can do something like:
JSONObject object = new JSONObject("keyvaluepairs");
for (Entry entry : keyValuePairs) {
object.put(entry.getKey(), entry.getValue();
}

Related

How to Traverse Complex JSON and put into a Map?

I tried few days to get this done. but could`t .
What i want is Traverse any given JSON and put Key and Value pair into a map. As a sample consider this JSON
String test = {
"RechargeRequest":{
"RechargeSerialNo":"2645",
"RechargeChannelID":"3",
"RechargeObj":{
"SubAccessCode":{
"PrimaryIdentity":"763500001"
}
},
"RechargeInfo":{
"CashPayment":[
{
"Amount":"30"
}
]
}
}
}
What i have tried so far
JSONObject jsonObj = new JSONObject(test);
Iterator<String> keys = jsonObj.keys();
Map<String,String> map = new HashMap<>();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObj.get(key) instanceof JSONObject) {
}else if(jsonObj.get(key) instanceof JSONArray){
}else{
}
}
Maps value should be like ( "RechargeChannelID","3")
( "Amount":"30")
Can anybody help me please?
Thanks,
If I understood correctly you want to flatten your json file into one level then map it to key and value pairs, kindly check the link below:
How to deserialize JSON into flat, Map-like structure?

Parsing unnamed nested arrays with minimal-json?

So I'm working on a fairly simple Java program which grabs market data from cryptocurrency exchanges and displays information to the user. I am using the minimal-json library.
Here is my current code:
public class Market {
static JsonArray arrayBittrex;
public static void startTimer(){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
String url = "https://bittrex.com/api/v1.1/public/getmarketsummaries";
try {
URL url2 = new URL(url);
URLConnection con = url2.openConnection();
InputStream in = con.getInputStream();
String encoding = "UTF-8";
String body = IOUtils.toString(in, encoding);
arrayBittrex = Json.parse(body).asObject().get("result").asArray();
}
catch(MalformedURLException e) {}
catch(IOException e) {}
}
}, 0,5000);
}
public static float getPrice(String exchange, String market) {
for (JsonValue item : arrayBittrex) {
float last = item.asObject().getFloat("Last", 0);
System.out.println(last);
return last;
}
return 0;
}
}
This code works with simple json, for example (from https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-ltc):
{
"success" : true,
"message" : "",
"result" : [{
"MarketName" : "BTC-LTC",
"High" : 0.01350000,
"Low" : 0.01200000,
"Volume" : 3833.97619253,
"Last" : 0.01349998
}
]
}
It will properly return the "Last" value in the array.
However, this cant work when the json has multiple arrays (like in https://bittrex.com/api/v1.1/public/getmarketsummaries):
{
"success" : true,
"message" : "",
"result" : [{
"MarketName" : "BTC-888",
"High" : 0.00000919,
"Low" : 0.00000820,
"Volume" : 74339.61396015,
"Last" : 0.00000820
}, {
"MarketName" : "BTC-A3C",
"High" : 0.00000072,
"Low" : 0.00000001,
"Volume" : 166340678.42280999,
"Last" : 0.00000005
}
]
}
So my question is: how can I get the "Last" value by searching for the array by the "MarketName" value?
Here is a direct & null-safe way to tackle this using Java 8 library Dynamics. We're going to parse the json into a Map, read that map dynamically to what we want.
So first we can use Jackson, Gson or something to convert json -> map.
// com.fasterxml.jackson.core:jackson-databind json -> map
Map jsonMap = new ObjectMapper()
.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
.readValue(jsonStringOrInputSourceEtc, Map.class);
We can now get a Dynamic instance. And, for example, grab the BTC-A3C - Last value.
Dynamic json = Dynamic.from(jsonMap);
BigDecimal a3cLast = json.get("result").children()
.filter(data -> data.get("MarketName").asString().equals("BTC-A3C"))
.findAny()
.flatMap(data -> data.get("Last").maybe().convert().intoDecimal())
.orElse(BigDecimal.ZERO);
// 5E-8
Or perhaps convert the whole lot into a map of MarketName -> Last value
Map<String, BigDecimal> marketNameLastValue = json.get("result").children()
// assume fields are always present, otherwise see #maybe() methods
.collect(toMap(
data -> data.get("MarketName").asString(),
data -> data.get("Last").convert().intoDecimal()
));
// {BTC-A3C=5E-8, BTC-888=0.00000820}
See more examples https://github.com/alexheretic/dynamics

How to properly uplevel a json key in java? Why is the json not changing?

I have an array "myarray" like this:
[{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}]
How do I uplevel it properly? Using minimal-json, I do the following:
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
The last line when I print out my jsonArray, it looks as if nothing has changed whatsoever. What am I doing wrong? I want to end up with the following:
[{
name: John,
age: 18
computer_skills: 4
mile_runner: 2
}]
I tried using this: https://github.com/ralfstx/minimal-json. Alternatives are welcome. I want to not have to create a model object that contains key value pairs for every single key value in my object within "myarray". I am used to python where everything is simple to access and replace.
After some researching I found out that your json array is invalid, there are quotes missing on at least the keys (See why do you need the quotes). Look at the same code you used but with modified input for 'myarray':
String myarray = "[{\"name\":\"John\",\"age\":{\"years\":18},\"computer_skills\":{\"years\":4},\"mile_runner\":{\"years\":2}}]";
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
This code prints:
[{"name":"John","age":18,"computer_skills":4,"mile_runner":2}]
what is the expected result.

Extracting an array from a JSON object

I have a JSON Object of the following and I need to parse the path strings inside the web array into an new JSON array.
"taxonomy": {
"source": {
"master": {
"_id": "5000",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
"web": [
{
"_id": "6686",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
{
"_id": "7686",
"path": "/Appliances/Refrigerators/Bottom Freezers"
}
],
},
},
I have written till this but I'm not sure how to get all the path inside the web array.
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
if(!jsonTaxonomy.isNull("source"))
{
JSONObject jsonTaxonomySource= jsonTaxonomy.optJSONObject("source");
if(!jsonTaxonomySource.isNull("web"))
{
JSONArray jsonTaxonomySourceWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySourceWeb!=null && jsonTaxonomySourceWeb.length()>0)
{
//Got inside the array
}
}
}
}
Without providing you with a full answer, I'm convinced you'll be able to find your answer by debugging this method and stopping it at the most inner if(). You'll be able to of what jsonTaxonomySearsWeb consists and thus how to get its values.
Modify your code to something like this:-
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
JSONObject jsonTaxonomySource = jsonTaxonomy.optJSONObject("source");
if(jsonTaxonomySource!=null)
{
JSONArray jsonTaxonomySearsWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySearsWeb!=null)
{
// Traverse through your JSONArray and get each Object & extract path from it.
}
}
}
I am bit unclear about the question. But As per my understanding you want to parse the JSON if you want to do that in java then you can use GSON jar from google...you can also check simple example here Gson handle object or array
Try like this...
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length(); i++) {
JSONObject c = groups.getJSONObject(i);
String source = c.getString(TAG_SOURCE);
System.out.println("Checking ::"+source);
String lname = c.getString(TAG_PATH);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SOURCE, source);
map.put(TAG_PATH,path);
weblist.add(map); //weblist is your arraylist for both values
webpathlist.add(path); //webpathlist is your arraylist for path
}
List<String> newList = new ArrayList<String>();
newList.addAll(weblist);

Parsing JSON, not sure on how and when to use iterators (Android Platform)

I have this JSON to parse
{"files_informations": {
"row":{"value":"artist1"},
"row":{"value":"artist2"}
}
}
I would like to know how can I get the first value artist1 and then the second one artist2
This is what I am doing :
JSONObject myObject = jObject.getJSONObject("files_informations");
JSONObject rowObject = myObject.getJSONObject("row");
Iterator<JSONObject> rowIt = rowObject.keys();
while (rowIt.hasNext()) {
JSONObject tmp = rowIt.next();
Log.e("", tmp.getString("value"));
}
I got java.lang.classCastException for this JSONObject tmp = rowIt.next();
So there are my two questions :
Do I need to use iterators in this
case ?
How do one should use them ?
Edit :
Should the JSON looks like this ?
{"files_informations": [
"row":{"value":"artist2"},
"row":{"value":"artist1"}
]
}
rowIt.next() is "row" String in this case.
Refactor your JSON to this:
{"files_informations":
[ {"value":"artist2"},
{"value":"artist1"} ] }
Or even this:
{ "files_informations": [ "artist2", "artist1" ] }
and then use:
JSONArray artistsArr = myObject.getJSONArray("files_informations");
for (int i = 0; i < artistsArr.size(); i++) {
// first case
Log.d(TAG, artistsArr.get(i).getString("value"));
// Second case
Log.d(TAG, artistsArr.getString(i));
}
Iterators are not supported in JSONArrays, however you can convert them to plain Java arrays/lists if you really need it.

Categories

Resources