question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

integer values of array become a float values

See original GitHub issue
public class Filter extends Object implements Serializable{

    private static final long serialVersionUID = 4944267946319467028L;  
    SparseArray<List<Integer>> catalogue = new SparseArray<List<String>>();

        ....
}

I'm filling catalogue variable with next values : {0=>{1,2,3,4}, 3=>{20,21,22} 
...}

Then I'm saving Filter object like this:
   ...
   ArrayList<Filter> filterList;
   .....

   public void saveFilter(Filter filterModel){      

      filterList.add(filterModel);

      Gson gson = new Gson();
      String jsonStr = gson.toJson(filterList);

      // For example save as
      preference = activity.getSharedPreferences("SJ_MAIN_STORAGE", Context.MODE_PRIVATE);
      Editor editor = preference.edit();
      editor.putString(key, jsonStr);       
      editor.commit();
   }    

I'm getting Filter object this way :
   public ArrayList<Filter> getFilter{
      Gson gson = new Gson();
      ArrayList<Filter> arrayList = new ArrayList<Filter>();    
      String json = preference.getString(key, "");
      if (hStrings.isEmpty(json)) return arrayList;

      JsonParser parser = new JsonParser();
      JsonArray array = parser.parse(json).getAsJsonArray();

      try{
    for(int i = 0; i < array.size(); i++)
    {
        arrayList.add(gson.fromJson(array.get(i), Filter.class));
    }
      }catch(Exception e){

      }
      return arrayList ;
   }

I have the next result of catalogue value: {0=>{1.0,2.0,3.0,4.0}, 
3=>{20.0,21.0,22.0} ...}

(integer values of array become a float values).
Is it right behavior?

Thank you.

Original issue reported on code.google.com by troshkov...@gmail.com on 12 Feb 2014 at 3:00

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
GoogleCodeExportercommented, Mar 19, 2015
I solved my problem 


public class JsonTest
{
    private static class IntegerFirstSOMapDeserializer
            implements JsonDeserializer<Map<String, Object>>
    {
        @Override
        public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
                throws JsonParseException
        {
            Map<String, Object> map = Maps.newLinkedHashMap();
            for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet())
            {
                JsonElement el = entry.getValue();
                Object o = null;
                try
                {
                    float f = el.getAsFloat();
                    // not loose precision
                    if (Math.ceil(f) == f)
                        o = (int) f;
                    else o = f;
                } catch (Exception ignored) {}
                if (o == null)
                    try {o = el.getAsString();} catch (Exception ignored) {}
                map.put(entry.getKey(), o);
            }
            return map;
        }
    }

    @Test
    public void test()
    {
        Map<String,Object> value = Maps.newHashMap();
        value.put("i",123);
        value.put("d",123.2f);
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(new TypeToken<Map<String, Object>>() {}.getType(), new IntegerFirstSOMapDeserializer())
                .create();


        Map o = gson.fromJson(gson.toJson(value), new TypeToken<Map<String, Object>>() {}.getType());
        System.out.println(o);
        assert o.get("i").equals(value.get("i"));
        assert o.get("d").equals(value.get("d"));
        o = gson.fromJson(gson.toJson(value), new TypeToken<Map<String, Float>>() {}.getType());
        System.out.println(o);
        assert !o.get("i").equals(value.get("i"));
        assert o.get("d").equals(value.get("d"));
    }
}

Original comment by wenerm...@gmail.com on 25 Sep 2014 at 7:45

0reactions
eamonnmcmanuscommented, Oct 9, 2021

Addressed by #1290.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why do numpy array turns int into float - Stack Overflow
Everything you put into the array gets converted to that type. By default, the data type is assumed to be float . To...
Read more >
Using NumPy to Convert Array Elements to Float Type
Method 1 : Here, we can utilize the astype() function that is offered by NumPy. This function creates another copy of the initial...
Read more >
How to Convert NumPy Array of Floats into Integers - Statology
This tutorial explains how to convert a NumPy array of floats to an array of integers, including several examples.
Read more >
Convert a NumPy array of float values to a ... - w3resource
Write a NumPy program to convert a NumPy array of float values to a NumPy array of integer values. Pictorial Presentation: Python NumPy:...
Read more >
Data types — NumPy v1.23 Manual
Complex number, represented by two single-precision floats (real and imaginary ... Data-types can be used as functions to convert python numbers to array...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found