Java中的JSON解码 [英] JSON decode in Java

查看:77
本文介绍了Java中的JSON解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一些这样的JSON代码:

I get some JSON code like this:

{"1":{"id":"1","Vorname":"x","Nachname":"y","MaleFemale":0,"interests":[]},
 "2":{"id":"2","Vorname":"x","Nachname":"y","MaleFemale":1,"interests":[]},
 ...

来自我的PHP脚本.您能告诉我如何用Java解码这种格式吗? 我只得到一些示例,其中您必须具有这样的格式:

from my PHP script. Could you tell me how to decode this format in Java? I only get examples where you have to have to have a format like this:

{"contacts": [{"user.id":"1","Vorname":"x","Nachname":"y","MaleFemale":1},
              {"user.id":"2","Vorname":"x1","Nachname":"y2","MaleFemale":0}]}

所以区别是在第一个给定的代码中没有主节点".在第二个给定的代码中,有一个(联系人").我需要这个节点吗?我做了很多尝试,但是我不知道如何解决这个问题.

So the difference is that in the first given code there is no "main node". In the second given code there is one ("contacts"). Do I need this node? I try so much but i do not get how to work this out.

非常感谢您.

推荐答案

您可以通过 Jackson Java库.这是示例代码片段.

You can do this easily with Jackson java library. Here is an example code snippet.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.IOException;

public class Test {

    public static void main(String[] args) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        // Reading the string to a JSON object
        JsonNode jsonObject = mapper.readTree("{\"contacts\": [{\"user.id\":\"1\",\"Vorname\":\"x\",\"Nachname\":\"y\",\"MaleFemale\":1},\n" +
                "              {\"user.id\":\"2\",\"Vorname\":\"x1\",\"Nachname\":\"y2\",\"MaleFemale\":0}]}");

        //Some basic querying
        JsonNode contacts = jsonObject.get("contacts");
        if (contacts.isArray()){
            ArrayNode contactsArray = (ArrayNode) contacts;
            for (JsonNode contact : contactsArray) {
                System.out.println(contact.get("user.id"));
            }
        }

    }
}

您可以从 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆