Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

android - Java, convert Byte Array to HashMap or JSON string

I'm making an Android App to manage a Unix computer remotely. The application also allows you to see real-time PC statistics (CPU temperature, CPU load, etc.). On the pc there is a Python server that through a socket sends a JSON string as a byte array to the app which contains the PC statistics, like this:

[123, 45, 67, 90, ...]

This is the contents of the byte array (I decoded it with a website):

{
    "author": "Anton",
    "type": "server info",
    "date": "08/01/2021",
    "content": "",
    "opt": {
        "cpu": {
            "freq": [3866.041875, 1600.0, 3900.0],
            "usage": [0.0, 0.0, 1.0, 2.0, 1.0, 1.0, 0.0, 2.0],
            "load": [0.5, 0.63, 0.61]
        },
        "memory": {
            "ram": [15.54, 12.01, 22.7, 2.85, 9.67]
        },
        "disks": {
            "ssd": [219.1, 13.0, 194.9, 6.3],
            "hdd": [0.0, 0.0, 0, 100.0]
        },
        "temps": {
            "core-0": [32.0, 85.0, 105.0],
            "core-1": [36.0, 85.0, 105.0],
            "core-2": [37.0, 85.0, 105.0],
            "core-3": [38.0, 85.0, 105.0]
        }
    },
    "attached": null
}

How can I transform the byte array into a structure like a HashMap or a JSON string, so that I can retrieve the PC statistics, and then view them in the App through ProgressiveBars?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to use the ObjectMapper from Jackson or any other JSON parser/serializer to achieve this. One option, using ObjectMapper is to just serialize the string directly into a hashmap like this:

byte src[] = getBytesFromServer();
ObjectMapper om = new ObjectMapper();
TypeReference<Map<String,Object>> tr = new TypeReference<Map<String,Object>> {};
Map<String,Object> val = om.readValue(src,tr);

There are a few variants of this that should be helpful to you. You can also achieve the same with other JSON libraries like GSon


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...