GVKun编程网logo

在 Swift 中解析嵌套的 JSON 并存储到结构中(swift json解析框架)

13

关于在Swift中解析嵌套的JSON并存储到结构中和swiftjson解析框架的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android-如何使用json库解析嵌套的JSON对象?、A

关于在 Swift 中解析嵌套的 JSON 并存储到结构中swift json解析框架的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android-如何使用json库解析嵌套的JSON对象?、Android使用Gson解析嵌套的JsonArray、fastjson可以解析嵌套的内部类吗?、go语言中使用struct解析嵌套的json等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

在 Swift 中解析嵌套的 JSON 并存储到结构中(swift json解析框架)

在 Swift 中解析嵌套的 JSON 并存储到结构中(swift json解析框架)

据我了解你的任务,你可以试试这个

struct Shoes: Decodable {

   // MARK: - Coding Keys

   private enum RootKeys: String,CodingKey {
      case item = "0"
   }

   private enum NestedKeys: String,CodingKey {
      case name = "productname"
   }

   // MARK: - Properties

   let name: String

   // MARK: - Decoding

   init(from decoder: Decoder) throws {
       let root = try decoder.container(keyedBy: RootKeys.self)
       let nested = try root.nestedContainer(keyedBy: NestedKeys.self,forKey: RootKeys.item)
    
       name = try nested.decode(String.self,forKey: .name)
   }
}

android-如何使用json库解析嵌套的JSON对象?

android-如何使用json库解析嵌套的JSON对象?

我想使用json库解析json对象.

    {
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "BlueBerry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        }

    }

解决方法:

使用JSON ..

JSONObject object = new JSONObject(yourString);
JSONObject batters = object.getJSONObject("batters");
JSONArray batter = batters.getJSONArray("batter");
for(int i = 0 ; i < batter.length() ; i++) { 
JSONObject object1 = (JSONObject) batter.get(i);
    String id = object1.getString("id");
}

Android使用Gson解析嵌套的JsonArray

Android使用Gson解析嵌套的JsonArray

我有一个嵌套的 JSONArray.我是gson的新人.我已经尝试了很多教程,但那些没有帮助.
编辑:

[
{
    "DivisionID": "2c0e9dc1-a6a7","DivisionName": "Qwerty","SubDivision": [
        {
            "SubDivisionID": "70c3ac53-eec6","SubDivisionName": "QW123","Vehicle": [
                {
                    "nopol": "00571564","LastUpdate": "Oct 10 2010 10:10AM","LastSpeed": 0,"LastLon": 106.82176,"Location": "KNowHERE"
                },{
                    "nopol": "352848020936627","LastUpdate": "Oct10201010: 10AM","LastLon": 10124.228,"Location": "KNowHERE2"
                }
            ]
        }
    ]
}
]

这就是我到目前为止的尝试方式.编辑:

public class Post {
@Serializedname("DivisionID")
private String divisionid;
@Serializedname("DivisionName")
private String divisionname;
@Serializedname("SubDivision")
private ArrayList<SubDivision> subdivisions;

public Post(String divisionid,String divisionname) {
this.divisionid = divisionid;
this.divisionname = divisionname;
}
// getter and setter ...

public class SubDivision {
@Serializedname("SubDivisionID")
private String subdivisionid;
@Serializedname("SubDivisionName")
private String subdivisionname;
@Serializedname("Vehicle")
private ArrayList<Vehicles> vehicles;

public SubDivision (ArrayList<Vehicles> vehicles) {
    this.vehicles = vehicles;
}
// getter and setter ...

public class Vehicles {
@Serializedname("nopol")
private String nopol;
@Serializedname("LastLon")
private String lastlon;
@Serializedname("LastUpdate")
private String lastupdate;
@Serializedname("Location")
private String location;

public Vehicles(String nopol,String lastlon,String lastupdate,String location) {
    this.nopol = nopol;
    this.lastlon = lastlon;
    this.lastupdate = lastupdate;
    this.location = location;
}
// getter and setter ...

这是我解析它的方式.编辑:

Type listType = new Typetoken<ArrayList<Post>>(){}.getType();
            beanPostArrayList = new GsonBuilder().create().fromJson(reader,listType);
            postList=new StringBuffer();
            for(Post post: beanPostArrayList){
                Log.d("topic asd: ",post.getDivisionid()+"");
               postList.append("\n id: "+post.getDivisionid()+
                       "\n divname: "+post.getDivisionname());

                Type listType2 = new Typetoken<ArrayList<SubDivision>>(){}.getType();
                SubdivArrayList = new GsonBuilder().create().fromJson(reader,listType2);
                postList2 = new StringBuffer();
                for(SubDivision subdiv: SubdivArrayList){
                    postList.append("\n id: "+subdiv.getSubdivisionid()+
                            "\n subdivname: "+subdiv.getSubdivisionname());

                    Type listType3 = new Typetoken<ArrayList<Vehicles>>(){}.getType();
                    vehicleArrayList = new GsonBuilder().create().fromJson(reader,listType3);
                    postList3 = new StringBuffer();
                    for(Vehicles vehic: vehicleArrayList){
                        postList.append("\n nopol: "+vehic.getnopol()+
                                "\n lastlon: "+vehic.getLastLon()+
                                "\n latupdate: "+vehic.getLastUpdate()+
                                "\n location: "+vehic.getLocation());
                    }
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
            txtPostList.setText(postList);
            txtSubdivList.setText(postList2);
            txtVehicList.setText(postList3);
        }
    }.execute();

问题是我不知道如何解析这个结构.我该怎么做?

解决方法

以下应该有效:

public class Example {

    public static void main(String[] args) {

        String s = ""; // THE JSON FROM THE NETWORK
        Gson gson = new Gson();
        Post[] posts = gson.fromJson(s,Post[].class);
        for( Post p : posts ){
            System.out.println(posts.toString() );
        }
    }

    public static class Post {

        @Serializedname("DivisionID")
        String divisionId;

        @Serializedname("DivisionName")
        String divisionName;

        @Serializedname("SubDivision")
        List<SubDivision> subDivisions;
    }

    public static class SubDivision {

        @Serializedname("SubDivisionID")
        String subDivisionId;

        @Serializedname("SubDivisionName")
        String subDivisionName;

        @Serializedname("Vehicle")
        List<Vehicle> vehicles;
    }

    public static class Vehicle {

        @Serializedname("nopol")
        String nopol;

        @Serializedname("LastUpdate")
        String lastUpdate; // should be a date!

        @Serializedname("LastSpeed")
        String lastSpeed;

        @Serializedname("LastLon")
        Double lastLon;

        @Serializedname("Location")
        String location;
    }
}

fastjson可以解析嵌套的内部类吗?

fastjson可以解析嵌套的内部类吗?

类图:


内部类:

public class D3 {

    private D1 d1;
    private D2 d2;

    public D1 getD1() {
        return d1;
    }

    public void setD1(D1 d1) {
        this.d1 = d1;
    }

    public D2 getD2() {
        return d2;
    }

    public void setD2(D2 d2) {
        this.d2 = d2;
    }

    @Override
    public String toString() {
        return "D3{" +
                "d1=" + d1 +
                ",d2=" + d2 +
                '}';
    }

    public class D1{

        private String a1;
        private List<D4> d4 = new ArrayList<>();

        public String getA1() {
            return a1;
        }

        public void setA1(String a1) {
            this.a1 = a1;
        }

        public List<D4> getD4() {
            return d4;
        }

        public void setD4(List<D4> d4) {
            this.d4 = d4;
        }

        @Override
        public String toString() {
            return "D1{" +
                    "a1='" + a1 + '\'' +
                    ",d4=" + d4 +
                    '}';
        }

        public class D4{

            private String a4;

            public String getA4() {
                return a4;
            }

            public void setA4(String a4) {
                this.a4 = a4;
            }

            @Override
            public String toString() {
                return "D4{" +
                        "a4='" + a4 + '\'' +
                        '}';
            }
        }
    }

    public class D2{

        private String a2;

        public String getA2() {
            return a2;
        }

        public void setA2(String a2) {
            this.a2 = a2;
        }

        @Override
        public String toString() {
            return "D2{" +
                    "a2='" + a2 + '\'' +
                    '}';
        }
    }
} 


测试类

@Test
    public void testFastJson(){
        String s = "{\"d1\":{\"a1\":\"1\",\"d4\":[{\"a4\":\"4\"},{\"a4\":\"5\"}]},\"d2\":{\"a2\":\"3\"}}".trim();
        D3 d3 = JSON.parSEObject(s,D3.class);
        System.out.println(d3);
    }


结果:能够正常进行解析

总结:fastjson可以解析嵌套的内部类,这样使用嵌套内部类的方式可以使程序看起来更清晰


还有一个问题:在使用嵌套内部类的时候报错

fastJson解析报错com.alibaba.fastjson.JSONException:create instance error,class json.TestFJson$...

解决方法是:将内部类加static修饰 具体原因不明

参考:fastJson解析报错com.alibaba.fastjson.JSONException: create instance error,class json.TestFJson$

go语言中使用struct解析嵌套的json

go语言中使用struct解析嵌套的json

go语言中使用struct解析嵌套的json

问题内容

无法使用 go lang 将嵌套 json 解析为结构对象

我有一个嵌套的 json 字符串,我想使用 go 语言中的结构体来解析它。 json 看起来像这样

{"action":"add","business":{"listid":123,"objecttags":[{"tagcode":"csharp","tagname":"codename","tagvalue":["2"],"tagtype":3},{"tagcode":"golang","tagname":"coding","tagvalue":["3"],"tagtype":3}]}}
登录后复制

我想用go语言解析json。 json 具有嵌套结构,因此我创建了以下代码中提到的结构

package main

import (
    "encoding/json"
    "fmt"
)


type objecttagslist struct {
    tagcode  string
    tagname  string
    tagvalue []string
}

type model struct {
    action   string `json:"action"`
    business struct {
        listid     int64  `json:"listid"`
        objecttags []objecttagslist `json:"objecttags"`
    } `json:"business"`
}

func main() {
    json := `{"action":"add","business":{"listid":123,"objecttags":[{"tagcode":"csharp","tagname":"codename","tagvalue":["2"],"tagtype":3},{"tagcode":"golang","tagname":"coding","tagvalue":["3"],"tagtype":3}]}}`

    var model model
    json.unmarshal([]byte(json), &model)

    fmt.println(model.action) // this prints correctly as "add"
        fmt.println(model.business.listid) // this prints correctly as "123"


    fmt.println(model.business.objecttags) // this does not print the objecttags. rather this prints the objecttags as "[{  []} {  []}]"


}
登录后复制

我无法将内部嵌套 json 的值获取到结构中。

我还尝试再次解组内部结构

立即学习“go语言免费学习笔记(深入)”;

var object []objecttagslist

//this gives error as cannot convert model.business.objecttags (variable of type []objecttagslist) to type []byte

json.unmarshal([]byte(model.business.objecttags), &object)
登录后复制

//错误,无法将 model.business.objecttags([]objecttagslist 类型的变量)转换为 []byte 类型

fmt.println(object)
登录后复制

这给了我一个错误 无法将 model.business.objecttags([]objecttagslist 类型的变量)转换为 []byte 类型。

如何将此 json 映射到结构中? 我想以这样的方式映射它,以便我可以使用像

这样的对象
model.Business.ObjectTags[0].tagCode //--> Should print/store "csharp"
model.Business.ObjectTags[0].tagValue[0] //--> Should print/store "2"
登录后复制

请帮忙


正确答案


您只能编组/取消编组“导出”字段——即可以在当前包外部访问的字段,这在 go 中意味着“以大写字母开头的字段”。因此,如果您要将代码修改为如下所示:

package main

import (
    "encoding/json"
    "fmt"
)

type objecttagslist struct {
    tagcode  string
    tagname  string
    tagvalue []string
}

type model struct {
    action   string `json:"action"`
    business struct {
        listid     int64            `json:"listid"`
        objecttags []objecttagslist `json:"objecttags"`
    } `json:"business"`
}

func main() {
    json := `
{
  "action": "add",
  "business": {
    "listid": 123,
    "objecttags": [
      {
        "tagcode": "csharp",
        "tagname": "codename",
        "tagvalue": [
          "2"
        ],
        "tagtype": 3
      },
      {
        "tagcode": "golang",
        "tagname": "coding",
        "tagvalue": [
          "3"
        ],
        "tagtype": 3
      }
    ]
  }
}
`

    var model model
    json.unmarshal([]byte(json), &model)

    fmt.println(model.action)
    fmt.println(model.business.listid)

    fmt.println(model.business.objecttags)
}
登录后复制

您将得到输出:

add
123
[{csharp codename [2]} {golang coding [3]}]
登录后复制

这里我们利用了 json 模块会自动将名为 tagcode 的键映射到名为 tagcode 的结构体字段的事实,但实际上我们应该明确:

type ObjectTagsList struct {
    TagCode  string   `json:"tagCode"`
    TagName  string   `json:"tagName"`
    TagValue []string `json:"tagValue"`
}
登录后复制

以上就是go语言中使用struct解析嵌套的json的详细内容,更多请关注php中文网其它相关文章!

关于在 Swift 中解析嵌套的 JSON 并存储到结构中swift json解析框架的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于android-如何使用json库解析嵌套的JSON对象?、Android使用Gson解析嵌套的JsonArray、fastjson可以解析嵌套的内部类吗?、go语言中使用struct解析嵌套的json的相关知识,请在本站寻找。

本文标签: